Reputation: 53
I'm looking for a way to map multiple properties to different "sections" of a JSon string using newtonsoft.
What I currently have is the following (doesn't work at all, but maybe you'll get a better idea of what I'm trying to accomplish):
public class example
{
[JsonProperty("this.is.an.example")]
public string ex { get; set; }
[JsonProperty("this.is.another")]
public string ex2;
}
While the corresponding JSon string might be structured like so:
{
"this" :
{
"is" : {
"an" : {
"example" : "this is the first value I want to return"
}
"another" : "this is the second value"
}
}
}
I want it this way so that I can easily deserialize several of these JSon strings like so:
example y = JsonConvert.DeserializeObject<example>(x);
//where x is the JSon string shown above and
//y.ex == "this is the first value I want to return"
//y.ex2 == "this is the second value
//Also note that example is the class name of the resulting object
Hopefully you can see what I'm trying to accomplish. Thanks in advance for any help, any input is appreciated!
Note:
After a bit of searching I found a similar question that didn't receive an answer. But maybe it'll help JSON.NET deserialize/serialize JsonProperty JsonObject
Upvotes: 0
Views: 1548
Reputation: 116108
You can simply use dynamic
keyword, instead of writing some complex code for custom deserialization.
string json = @"{""this"":{""is"":{""an"":{""example"":""this is the first value I want to return""}}}}";
dynamic jObj = JObject.Parse(json);
string example = jObj.@[email protected];
PS: Since this
and is
are reserved-words in c# I used @
in front of them .
Upvotes: 2