如何反序列化JSON文本?

时间:2015-07-08 14:06:31

标签: c# json

我有使用Json数据的项目,我尝试反序列化这样的Json数据:

[{"232":{"id":"232","reference":"022222","name":"Poire","content_title":"","content":"","pv_ttc":"230","picture_1":"","picture_2":"","picture_3":"","picture_4":"","picture_5":""}}]

如果我正确理解Json,我们在开始时有一个索引,然后是一个名称参考价格等的子板。

那么,如何将此文本反序列化为对象?

知道我的班级是这样的:

public class productClass
{
    public string id {get;set;}
    public string reference { get; set; }
    public string name { get; set; }
    public string content_title{ get; set; }
    public string content { get; set; }
    public float pv_ttc{get;set;}
    public string picture_1{get;set;}
    public string picture_2{get;set;}
    public string picture_3{get;set;}
    public string picture_4{get;set;}
    public string picture_5{get;set;}

    public List<productClass> urlResult;

    public productClass ( )
    {
    }

    public productClass (string _id, string _reference, string _name, string _content_title, string _content, float _pv_ttc, string _picture_1, string _picture_2, string _picture_3, string _picture_4, string _picture_5)
    {
        id = _id;
        reference = _reference;
        name = _name;
        content_title = _content_title;
        content = _content;
        pv_ttc = _pv_ttc;
        picture_1 = _picture_1;
        picture_2 = _picture_2;
        picture_3 = _picture_3;
        picture_4 = _picture_4;
        picture_5 = _picture_5;
        urlResult = new List<productClass> ( );
    }

    public void addUrl ( List<productClass> urlResult )
    {
        foreach ( productClass _url in urlResult )
        {
            urlResult.Add ( _url );
        }
    }       
}

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

@sachou您考虑过使用JSON.Net吗?对于.Net来说,它是一个非常好的框架,您可以轻松地将JSON字符串反序列化为C#对象。您可以查看文档,但这是一个来自网站的简单示例:

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

我希望这会有所帮助。

答案 1 :(得分:1)

我建议您使用类似的JSON框架 Newtonsoft JSON.NET

您可以非常轻松地序列化和反序列化JSON对象,如下所示:

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

仔细查看Serializing/Deserializing JSON with JSON.net

答案 2 :(得分:0)

这是我的例子。我使用谷歌地图api作为例子

我创建了与谷歌地图相对应的以下类

public class AddressComponent
{
   public string long_name { get; set; }
   public string short_name { get; set; }
   public List<string> types { get; set; }
}

public class Result
{
    public List<AddressComponent> address_components { get; set; }
    public List<string> types { get; set; }
}

public class RootObject
{
    public List<Result> results { get; set; }
    public string status { get; set; }
}

然后我创建了这个方法

 public string GetZipCodeBasedonCoordinates()
{
    string zip = "";
    string url2 = @"https://maps.googleapis.com/maps/api/geocode/json?latlng=37.423021, -122.083739&sensor=false";

    System.Net.WebClient web = new System.Net.WebClient();
    var result = web.DownloadString(url2);

    RootObject root = JsonConvert.DeserializeObject<RootObject>(result);

    var allresults = root.results;
    foreach (var res in allresults)
    {
        foreach (var add in res.address_components)
        {
            var type = add.types;
            if (type[0] == "postal_code")
            {
                zip = add.long_name;

            }
        }
    }
    return zip;
}

您可以到这里查看我已解析的结果json https://maps.googleapis.com/maps/api/geocode/json?latlng=37.423021,%20-122.083739&sensor=false

答案 3 :(得分:0)

有关更多信息,请参阅我的反序列化方法:

public IEnumerator loadProducts (int cat)
{
    List <int> catNoTri = new List<int> ();
    catNoTri.Add (0);
    gm.totalPriceItem.Clear();
    isLoading = true;
    WWW www = new WWW ( urlProduct );
    yield return www;
    Debug.Log(www.text);
    string json = www.text.ToString ( );
    IndexPrductClass myJson = JsonReader.Deserialize<IndexPrductClass> ( json );
    foreach (productClass item in products) 
    {
        for (int i = 0; i < products.Length; i++) 
        {
            Debug.Log("product.productValue[i] = " + products[i].name);
        }
        if (firstLoad || gm.catId == 0) 
        {
            Debug.Log ("here1");
            nameProduct.Add (item.name);
            Debug.Log("item.name = " + item.name);
            idProduct.Add (item.id);
            prixItem.Add (item.pv_ttc);
            Debug.Log("item.pv_ttc = "  + item.pv_ttc);
            gm.totalPriceItem.Add (0);
            gm.qte = new int [gm.totalPriceItem.Count];
            descriptifProduct.Add (item.content);
            Debug.Log(" item.content = " +item.content);
        }
        else if (!firstLoad) 
        {
            Debug.Log ("here2");
            nameProduct.Add (item.name);
            idProduct.Add (item.id);
            prixItem.Add (item.pv_ttc);
            gm.totalPriceItem.Add (0);
            gm.qte = new int [gm.totalPriceItem.Count];
            descriptifProduct.Add (item.content);
        }
    }
    gm.canLoad = true;
}