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?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With