JSON deserialization in C# sub array -
i'm trying desearialize following using newtonsoft.json
{ "max_id_str":"1234567", "results":[{ "created_at":"tue, 21 may 2013 03:06:23 +0000", "from_user":"name here", "from_user_id":33333, "text":"the text goes here" }], "results_per_page":1, "since_id":0, "since_id_str":"0" }
i can retrieve max_id_str using desearialization cannot of data in "results"
here's code have
public class tweet { public string max_id_str { get; set; } public string text{ get; set; } public string results_per_page{ get; set; } public string since_id { get; set; } public string since_id_str { get; set; } }
i create object of class , attempt desearlize object
tweet t = new tweet(); t = jsonconvert.deserializeobject<tweet>(e.result);
everything "text" populates? text's value null when output value. ideas how accomplish i'm trying?
i'm not sure you're expecting deserializing json string type, text
not property of object there's no reason expect that. text
property of objects within results
list. need map objects , access text through result
objects.
public class tweet { public string max_id_str { get; set; } //public string text{ get; set; } public list<result> results { get; set; } public string results_per_page{ get; set; } public string since_id { get; set; } public string since_id_str { get; set; } } public class result { public string created_at { get; set; } public string from_user { get; set; } public int from_user_id { get; set; } public string text { get; set; } }
if trying use values within results determine value of text property, write converter extract text value. add jsonproperty
, jsonconverter
attribute text
property , implement converter.
public class tweet { public string max_id_str { get; set; } [jsonproperty("results")] [jsonconverter(typeof(textpropertyresultextractorconverter))] public string text { get; set; } public string results_per_page{ get; set; } public string since_id { get; set; } public string since_id_str { get; set; } } public class textpropertyresultextractorconverter : jsonconverter { public override bool canconvert(type type) { throw new notimplementedexception(); } public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer) { var results = (jarray)serializer.deserialize(reader); var result = results.first(); return result.value<string>("text"); } public override void writejson(jsonwriter writer, object value, jsonserializer serializer) { throw new notimplementedexception(); } }
Comments
Post a Comment