Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize malformed JSON with JSON.NET [duplicate]

Tags:

c#

json.net

I have a snippet of JSON that looks like this:

{"123":{"name":"test","info":"abc"}}

The 123 is an ID and can change on each request. This is beyond my control.

I want to Deserialize the JSON using JSON.NET. I have tried:

 User u = JsonConvert.DeserializeObject<User>(json);

However, this does not work unless I define the JsonProperty attribute like so:

[JsonProperty("123")]
public string ID { get; set; }

But of course I cannot actually do this because the ID 123 will change on every request.

How can I read the ID property using JSON.NET and apply it to the ID class?

like image 841
Barry Kaye Avatar asked Jun 15 '15 13:06

Barry Kaye


2 Answers

Try this:

var json = "{\"123\":{\"name\":\"test\",\"info\":\"abc\"}}";

var rootObject = JsonConvert.DeserializeObject<Dictionary<string, User>>(json);
var user = rootObject.Select(kvp => new User 
                                    { ID = kvp.Key, 
                                      Name = kvp.Value.Name, 
                                      Info = kvp.Value.Info 
                                    }).First();

This does have some unnecessary overhead, but considering the circumstances, it would do.

like image 55
Yuval Itzchakov Avatar answered Sep 27 '22 17:09

Yuval Itzchakov


I'd do it this way:

dynamic result = JsonConvert.DeserializeObject(json);

var myObject = result as JObject;
var properties = myObject.Properties();
var property = properties.FirstOrDefault(); // take first element 
string name = property.Name;

foreach (var item in properties)
{
    var jProperty = item as JProperty;
    var nestedJson = jProperty.Value.ToString();
    dynamic nestedResult = JsonConvert.DeserializeObject(nestedJson); // or put it into a model/data structure
}
like image 44
stefankmitph Avatar answered Sep 27 '22 18:09

stefankmitph