.net调用json

数据如下:

{"cacheCount":1,"count":"34","slice":"5, 5","list":[1001598,1001601,1001605,1001609,1001612],"page":1,"error":200}

 

采用第三方组件

Jayrock 和 Jayrock.Json

首先引入命名空间

using Jayrock.Json;

其次,创建 JsonObject 对象,步骤如下:

string strJsonText = @"{"cacheCount":1,"count":"34","slice":"5, 5","list":

[1001598,1001601,1001605,1001609,1001612],"page":1,"error":200}";

JsonReader reader = new JsonTextReader(new StringReader(strJsonText));

JsonObject jsonObj = new JsonObject();
jsonObj.Import(reader);

这样,就将一个文本的JSon数据转变成一个对象,如果要获取 count 的值,则可以这样

string count = jsonObj["count"].ToString();

但是有个问题,list 是一个数组,该如何获取呢?不用急,Jayrock已经为我们准备好了,来看

using (JsonTextReader textReader = new JsonTextReader(new StringReader(jsonObj["list"].ToString())))
{
    while (textReader.Read())
    {
        if (!string.IsNullOrEmpty(textReader.Text))
        {
            Response.Write(textReader.Text);
        }
    }
}

将数组的内容再赋予一个JsonTextReader对象 ,利用其Read方法进行逐行读取就OK了

当然,你也可以使用 JsonArray 对象,这里就不再叙述了

protected void Button1_Click(object sender, EventArgs e)
{
    string str = "{\"order\":{\"orderNO\":\"PO08120200038\",\"postTime\":\"2008-12-2 15:08:36\",\"sender\":\"联想\",\"receiver\":\"华为科技有限公司a\",\"agent\":\"深圳市怡亚通供应链股份有限公司\",\"customerOrderNO\":\"sdfdsf\",\"senderLinkman\":\"吴可立联想\",\"receiverLinkman\":\"所有商务人员\",\"productList\":[{\"productName\":\"商品3\",\"productQuantity\":\"34\",\"productUnitPrice\":\"34\",\"productTotalPrice\":\"1156\"}],\"orderTotalPrice\":\"1,156.0000\",\"orderCurreny\":\"人民币\",\"balanceCurreny\":\"人民币\",\"fetchAddress\":\"\",\"deliveryMode\":\"\",\"deliveryTime\":\"\",\"receiverLinkman\":\"\",\"receiverContact\":\"\",\"orderDescript\":\"dfsdf\",\"orderRemark\":\"\"}}";
    //解密Json,获取数据Begin
    //string hxw = CACheck.DecodeCA(this.hidCAString.Value);
    JsonReader reader = new JsonTextReader(new StringReader(str));
    
    JsonObject jsonObj = new JsonObject();
    jsonObj.Import(reader);
    
    //这样,就将一个文本的JSon数据转变成一个对象,如果要获取 count 的值,则可以这样
    
    string count = jsonObj["order"].ToString();
    
    JsonReader reader2 = new JsonTextReader(new StringReader(count));
    JsonObject jsonObj2 = new JsonObject();
    jsonObj2.Import(reader2);
    
    string count2 = jsonObj2["orderNO"].ToString();
    string count3 = jsonObj2["postTime"].ToString();
    
    Response.Write(count2+"---"+count3);
}

 

posted @ 2008-05-07 17:42  CoderWayne  阅读(438)  评论(0编辑  收藏  举报