The simple attribute that maps the json sub -attribute to the C# object
Create a customized back -sequentialized behavior in Newtonsoft.json can be achieved by custom attributes and converters. This allows you to map the sub -attributes of the JSON object to the simple attributes of the C# class, even if they do not have the corresponding object.
Use the auxiliary method
If you only need an additional attribute, a simple method is to resolve your JSON as jobject, fill your class with ToObject (), and then use selecttoken () to extract the additional attributes. For example:
Create a custom JSONCONVERter
<code class="language-csharp">string json = @" { ""name"" : ""Joe Shmoe"", ""age"" : 26, ""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>
For more complicated solutions, you can create a custom JSONCONVERter that uses the above technology to process all attributes marked with JSONPROPERTY attributes. JSONCONVER can use reflection to find attributes, map them to the correct JSON path, and fill the attributes accordingly.
The associated custom converter
<code class="language-csharp">class JsonPathConverter : JsonConverter { // ReadJson 实现在此处... }</code>
After using these attributes, you can derive JSON as usual, and the mapping will occur automatically.
The above is the detailed content of How to Map Nested JSON Properties to Simple C# Properties?. For more information, please follow other related articles on the PHP Chinese website!