在C#中解析JSON对象

时间:2012-04-01 08:44:59

标签: c# json

我使用JSON.NET并且我想解析从WebService获得的以下对象。有人可以发布一个如何做到这一点的例子吗?

@"{""MessageType"":0,
   ""Message"":""Success"",
   ""Value"":[
              {""listId"":1,
               ""listName"":""DemoList"",
               ""itemInList"":[
                    {
                     ""fromDate"":""\/Date(1228946400000)\/"",
                     ""fromLocation"":null,
                     ""toLocation"":null,
                     ""originalRequest"":""water"",
                     ""creationDate"":""\/Date(1339448400000)\/"",
                     ""typeId"":1
                    },
                    {
                     ""fromDate"":null,
                     ""fromLocation"":null,
                     ""toLocation"":null,
                     ""originalRequest"":""gala"",
                     ""creationDate"":""\/Date(1304370000000)\/"",
                     ""typeId"":1
                    }
              ]}
    ]}"

JSON对象

{
  "MessageType":0,
  "Message":"UserLists",
  "Value":
          [
            {
              "listId":1,
              "listName":"DemoList",
              "itemInList" 
                    [
                      {
                         "fromDate":"\/Date(1228946400000)\/",
                         "fromLocation":null,
                         "toLocation":null,
                         "originalRequest":"water",
                         "creationDate":"\/Date(1339448400000)\/",
                         "typeId":1
                      },
                      {
                         "fromDate":null,
                         "fromLocation":null,
                         "toLocation":null,
                         "originalRequest":"gala",
                         "creationDate":"\/Date(1304370000000)\/",
                         "typeId":1
                       }
                  ],
                  "numberOfItems":2
              }
          ]
     }

感谢。

2 个答案:

答案 0 :(得分:7)

您需要创建一个这样的实体:

public class Entity
{
    public int MessageType { get; set; }
    public string Message { get; set; }
    public List<EntityValue> Value { get; set; }
}

public class EntityValue
{
    public int listId { get; set; }
    public string listName { get; set; }
    public List<ItemInList> itemInList { get; set; }
}

public class ItemInList
{
    public DateTime? fromDate { get; set; }
    public string fromLocation { get; set; }
    public string toLocation { get; set; }
    public string originalRequest { get; set; }
    public DateTime creationDate { get; set; }
    public int typeId { get; set; }
}

实体必须具有与json数据相同的结构。 你可以调用方法:

JsonConvert.DeserializeObject<Entity>(json);

如果有任何异常,您需要调整实体直到它起作用。

答案 1 :(得分:0)

请阅读以下链接,了解metro样式应用程序中的parsi。 http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh770287.aspx