Reputation: 47965
I get from a external source a json with TONS of fields. I don't care about most of them, I just need "some" of them. (which are at different child-level).
So I don't need to have a "strong type" oject I guess. Tried with:
JavaScriptSerializer js = new JavaScriptSerializer();
var obj = jss.Deserialize(myJson);
but seems I can't doing it? How can I do it?
Using:
jss.Deserialize<dynamic>(objectText);
than I can't use LINQ to search the fields...
Upvotes: 0
Views: 6789
Reputation: 2895
You can create class and omit fields that you don't need.
But I would suggest to have class to have more control on (de)serialization.
As already suggested, JSON.NET is one of the best library for this kind of task.
Check out below link that shows how to deserialize json to object and then get the values:
https://stackoverflow.com/a/5502317/309395
Upvotes: 0
Reputation: 67296
With JSON.Net, you can deserialize to an object that you define. The object that you define can be only a partial match. The DeserializeObject<>
will then ignore all the other JSON fields.
For example JSON:
{
Cat: "Tom",
Mouse: "Jerry",
Duck: "Donald"
}
Using this:
public class LooneyTunes
{
public string Cat { get; set; }
public string Mouse { get; set; }
}
var looneyTunes = JsonConvert.DeserializeObject<LooneyTunes>(json);
This will ignore the Duck
property and deserialize the rest correctly. So, using this technique you can select what part of the JSON message you are interested in.
Upvotes: 6
Reputation: 4895
Try using Newtonsoft Json.NET, it has a dynamic JObject which can interpret pretty much anything also if it is a List of subvalues you will be able to query them with LINQ.
Upvotes: 2