-2

I have project which uses Json data, I try deserialize a Json data like this:

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

If I correctly understand Json, at the beginning we have an index, then a sub-board with the name the reference the price etc.

Well, how to deserialize this text to object?

Knowing that I have my class as this:

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 );
        }
    }       
}

Thanks for help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sachou
  • 1
  • 1
  • `Well, how to deserialize this text to object?` search for "[JSON deserialization C#](https://www.google.com/#q=JSON+deserialization+C%23)" on your favorite search engine and you'll no doubt find a ton of resources. JSON.Net is one of the best libraries for doing this. DO NOT try and parse JSON yourself from the string. – Matt Burland Jul 08 '15 at 14:18
  • possible duplicate of [Deserialize JSON with C#](http://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) – Matt Burland Jul 08 '15 at 14:19

4 Answers4

1

@sachou have you considered using JSON.Net? It is a really nice framework for .Net and you can easily de-serialize JSON strings into your C# objects. You can have a look in the documentation, but here is a simple example from the website:

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);

I hope this helps.

Bazindrix
  • 1,041
  • 8
  • 8
1

I'd suggest you use a JSON Framework like Newtonsoft JSON.NET

You can very easily serialize and deserialize JSON objects like this:

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);

Take a closer look at Serializing/Deserializing JSON with JSON.net

xeraphim
  • 4,375
  • 9
  • 54
  • 102
  • This is a comment rather than an answer and almost exactly the same as the existing answer from @Bazindrix – Matt Burland Jul 08 '15 at 14:20
  • I'm sorry that it actually takes some time to write an answer and that someone posted the same example from the website while I was writing it. I cant foresee the future – xeraphim Jul 08 '15 at 14:21
0

Here is my example. I am using google map api as an example

I create following class corresponding to google maps

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; }
}

Then I created this method

 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;
}

You can go here to see the resulting json that I have parsed https://maps.googleapis.com/maps/api/geocode/json?latlng=37.423021,%20-122.083739&sensor=false

kdnerd
  • 341
  • 3
  • 10
  • I use your solution but th compiler return me : `InvalidCastException: Cannot cast from source type to destination type. JsonFx.Json.JsonReader.Deserialize[IndexPrductClass] (System.String value)`. Sorry It's my first work with Json data and I'm a little lost. – sachou Jul 08 '15 at 14:56
  • did you add assembly reference using Newtonsoft.Json? – kdnerd Jul 08 '15 at 18:40
  • Check the code here http://goo.gl/X5M8Ts You can download reference in Visual Studio by going to TOOLs> Library Package Manager > Manage Nuget Pacakges For Solution then do an online search for Newtonsoft – kdnerd Jul 08 '15 at 18:56
  • I develop with Unity, Can I use newtonsoft.Json ? – sachou Jul 09 '15 at 07:05
0

For more informations, see my deserialize's method :

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;
}
sachou
  • 1
  • 1