When encountering JSON data with a layered structure, you may want to map the sub -attributes of JSON complex objects to the simple attributes in the class. Although the newTonsoft.json framework provides
attributes to mappore the original JSON data, it does not support mapping attributes.
[DataMember]
However, there are some ways to achieve this mapping. A simple method is to sequence JSON back to
to retrieve the required sub -attributes. JObject
SelectToken
For example, consider the following JSON data:
To map the
<code class="language-json">{ "picture": { "id": 123456, "data": { "type": "jpg", "url": "http://www.someplace.com/mypicture.jpg" } } }</code>
url
ProfilePicture
If you need a more advanced solution, you can customize
<code class="language-csharp">string json = @" { ""picture"": { ""id"": 123456, ""data"": { ""type"": ""jpg"", ""url"": ""http://www.someplace.com/mypicture.jpg"" } } }"; JObject jo = JObject.Parse(json); Person p = jo.ToObject<Person>(); p.ProfilePicture = (string)jo.SelectToken("picture.data.url");</code>
JsonConverter
For example, consider the following JSON data: JsonProperty
To deserture JSON and map the sub -attributes to the simple attributes in the class, you can use the following custom converter:
<code class="language-json">{ "name": "Joe Shmoe", "age": 26, "picture": { "id": 123456, "data": { "type": "jpg", "url": "http://www.someplace.com/mypicture.jpg" } }, "favorites": { "movie": { "title": "The Godfather", "starring": "Marlon Brando", "year": 1972 }, "color": "purple" } }</code>
With a custom converter, you can recal the json as usual as usual:
<code class="language-csharp">[JsonConverter(typeof(JsonPathConverter))] class Person { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("age")] public int Age { get; set; } [JsonProperty("picture.data.url")] public string ProfilePicture { get; set; } [JsonProperty("favorites.movie")] public Movie FavoriteMovie { get; set; } [JsonProperty("favorites.color")] public string FavoriteColor { get; set; } }</code>
The above is the detailed content of How to Map Nested JSON Properties to Class Properties in C#?. For more information, please follow other related articles on the PHP Chinese website!