Domanda

I try to convert from json to c# class object, cause my final step will be put this all data into local db. I have no problem with taking this data like one big string, so the Url is good typed, but it's not my goal.

this is the json data, here we have two objects

[{"id":"1","category":"1","name":"good 1","prize":"12.3","prize2":"13.4","elements":"row,column,paper","secid":"2131","description":"nice","quality":"best","dateofcoming":"2013-12-20 18:08:50","date":"2013-12-20 00:00:00"},
{"id":"2","category":"2","name":"good","prize":"14.3","prize2":"15.4","elements":"up,down,left","secid":"2132","description":"nc","quality":"best","dateofcoming":"2013-12-20 18:10:55","date":"2013-12-20 00:00:00"}]

I try by this way which I found in the book:

  private void getBookData()
    {
        // we creating the request details to the site which give us 
        // back the json data 
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("here is my adress");
       request.Accept = "and header";
        // starting the request
        request.BeginGetResponse(callback_with_food_info, request);
    }

    private void callback_with_food_info(IAsyncResult ar)
    {

        HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
        // we get the response
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);

        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(ListOfObjects));

        Stream responseStream = response.GetResponseStream();

        ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
        String fsdfsdf = "how how how";



    }

and in the row when we ReadObject

 ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);

I get exception "System.InvalidCastException", my List class look like this and it was created by http://json2csharp.com/

  public class DetailsOfObject
   {  
    public string id { get; set; }
    public string category { get; set; }
    public string name { get; set; }
    public string prize { get; set; }
    public string prize2 { get; set; }
    public string elements { get; set; }
    public string secid { get; set; }
    public string description { get; set; }
    public string quality { get; set; }
    public string dateofcoming { get; set; }
    public string date { get; set; }
}

public class ListOfObjects 
{
    public DetailsOfObject list {get; set;}
}

Any advice how to finally convert this json data

È stato utile?

Soluzione

You need to add Data attributes to model

 [DataContract]
 public class DetailsOfObject
 {
    [DataMember] 
    public string id { get; set; }

and change deserialize line

List<DetailsOfObject> listOfobj = (List<DetailsOfObject>)deserializer.ReadObject(responseStream);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top