How to deserialize a nested json object into a primitive type based on one of the nested object's field

Related searches

Say I have this piece of json:

[{
    "id": 123,
    "description": "test",
    "group": {
        "id": 456,
        "description": "org"
    }
}]

I want to deserialize the JObject above into a C# object. Traditionally I have worked out something like this (where jObject is a JObject loaded from the json string above):

public class Item
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("group")]
    public Group Group { get; set; }

}

public class Group
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

}

var foo = jObject.ToObject<Item>();

What if in the Item class, I just wanted to have a field called GroupId of type int which simply stores the id field from the nested Group object? It would be simple enough to create a method to extract that value onto a field called 'GroupId' in Item, but because the json I'm dealing with has a lot of similarly nested objects where I'm only interested in the id, I'm wondering if I can use JsonSerializer class to accomplish populating a 'GroupId' field automatically upon deserialization somehow? Or if there is another method within the Newtonsoft.Json package that I might not be aware of.

I haven't worked with processing Json extensively, so apologies if this is 100-level stuff; I couldn't find anything that directly addressed this question specifically.

Since you are using Newtonsoft.Json, I will explain using the same.

When I need to get JSON that is used ONLY for my logic, I tend to do something like this:

For your Item class, what you want to do two things. One, not have to manually set it every time. Two, not have any serialization fail due to that value not being recognized or whatnot.

The first step is to use an Expression Body. This is basically going make the property that you want to act as a simple method, but work just like a property. The second step is simply adding the [JsonIgnore] attribute:

So your Item class becomes this:

public class Item
    {
        /// <summary>
        /// Property that will be left out of deserialization, but return the Group.Id every time the value is
        /// evaluated.
        /// </summary>
        [JsonIgnore]
        public int GroupId => (int)Group?.Id;

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("group")]
        public Group Group { get; set; }
    }

Notice the "GroupId" property that is now part of the items class. What the question mark after the "Group" property will do is ensure that the Group object is not null before attempting to evaluate the id property.

Using your JSON from above, I have just tested this myself in a unit test:

Please let me know if you need more information about any of the above.

Jsonconverter nested objects, Json namespace has built-in converters for most primitive types that map to In this tip, I will show how to import two nested JSON object files into SSIS using a couple A JsonConverter that determines the type of the deserialized object by its a property of the "base" object (the partial one), we additionally store its name. Assumes the JSON contains an array of objects and each object may contain a "name" property of type string. Counts objects and "name" property values that end with "University". Assumes the file is encoded as UTF-16 and transcodes it into UTF-8. A file encoded as UTF-8 can be read directly into a ReadOnlySpan<byte>, by using the following code:

you should use the statement like : var foo = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Item>>(jObject.ToString());

The first point is JSON looks like an array of objects, so you should be use collection when the time of parsing like List<Item> here.

You can use jobject but in this case, you need to convert it to string like jObject.ToString() here, Or you can pass JSON string directly to the function.

After it you can get the Group Id value by index like :- var GroupId = foo[0].Group.Id;

Nested Json Object, In C# how to deserialize nested json data. fieldname and the JSON field to parse, Example 39-1 shows a JSON object that represents a purchase order, with Instead of using a class based mapping like toJSON and fromJSON, the other nested dict s, arrays, booleans, or other primitive types like integers and strings. I have added a List<Rules> property to the rules class, but then I get this error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Data.Rule' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly. – jason

If you want to transform the group JSON object to a single value, assigning it to a property, you can use a custom JsonConverter.

Here, the custom ObjectToValueConverter is assigned to the GroupId property, decorated with [JsonProperty("group")]. When the object corresponding to group is deserialized, the custom converted is called and it will return the Value of the object's id Property, if present, converted to int. otherwise 0.

The Group class is not used anymore:

var myItems = JsonConvert.DeserializeObject<List<Item>>(json);

If you instead prefer to preserve the Group class object, do what Kuroiyatsu is suggesting.


public class Item
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("group")]
    [JsonConverter(typeof(ObjectToValueConverter))]
    public int GroupId { get; set; }
}

class ObjectToValueConverter : JsonConverter
{
    public override bool CanConvert(Type objectType) => true;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        if (token.Type == JTokenType.Object && ((JObject)token).ContainsKey("id")) {
            return (int)token["id"];
        }
        return 0;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
        => throw new NotImplementedException();
}

Nested Json Object, Start reading the JSON objects one by one, based on their type i. JSON can store nested objects in JSON format in addition to nested arrays. VS 2010 DeserializeAnonymousType & Nested JSON Object If this is your first can contain other nested dict s, arrays, booleans, or other primitive types like integers and strings. Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormsApplication1.Models+Usermachine]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

Serialization Guide, The Json.NET serializer can serialize a wide variety of .NET objects. This guide Summary; Complex Types; Primitive Types; Breakdown of Type Serialization NET will throw an error if it encounters incorrect JSON when deserializing a value . String (Serializing Dates in JSON). Byte[]. String (base 64 encoded). Type. One way to deserialize a json string recursively into dictionaries and lists with JSON.NET is to create a custom json converter class that derives from the JsonConverter abstract class provided by JSON.NET. It is in your derived JsonConverter where you put the implementation of how an object should be written to and from json.

Nested Json Object, Unlike other cmdlets that output objects one at a time, its output was a single object (which happened to be an array). Now the jQuery Forum. parse() which also preserves the JSON data type, e. Represents a Start reading the JSON objects one by one, based on their type i. In C# how to deserialize nested json data. Deserialize an Anonymous Type. Deserialize an Object This sample deserializes JSON to an object. Sample. Types. Copy.

Failed to deserialize JSON to MyAnswer: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ssSvgDesignViewer.RestRecords.JSONSTAnswerItemStructure' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

Comments
  • Works perfectly!
  • This is a great solution, but I'm interested in preserving the class objects as well.
  • Sure. I've posted it because this option was missing. It could be useful in some other scenario.