Home > Software engineering >  Deserializing JSON Nested Dictionaries
Deserializing JSON Nested Dictionaries

Time:12-22

My JSON message has a combination of a string, list and a nested dictionary, as seen below.

message = {
        "series":"A",
        "series_color": ["red","blue","green"],
        "parts":{"part1":{"id-01":"contextA", "id-02":"contextB", "id-03":"contextC"},"part2":{"id-01":"contextA", "id-02":"contextB", "id-03":"contextC"}}
          } 

This is received in a C# script in Unity where I deserialize this by using:

// Translates Byte into String
var Message = System.Text.Encoding.Default.GetString(e.Message);

// Translates String into Object and stores in Dictionary
Dictionary<string, object> MessageDICT = JsonConvert.DeserializeObject<Dictionary<string, object>>(Message);

From here I can print out the first two messages series and series_color.

// Series
object series= MessageDICT["series"];
print(series);

// Series Color
object series_color = (JArray)MessageDICT["series_color"])[0]
print(series_color)

The problem comes where I try to unpack the contents of the nested dictionary parts, as I can't unpack it due to its unexpected values such as "{".

I know there are manual methods of trying to replace "{" with "[" and using it as an array, as well as creating a class to read the JSON (shows errors regarding Unity main thread) however these are not the solution I am looking for.

Are there are any ways to unpack all of this? Thanks in advanced.

CodePudding user response:

you don't need to deserialize json, you can access to "parts" using parsing

Dictionary<string,object> MessageDICT = JsonConvert.DeserializeObject<Dictionary<string,object>>(json);

Dictionary<string,object> parts= ((JObject)MessageDICT["parts"]).Properties()
.SelectMany(i => new Dictionary<string, object> { {i.Name,i.Value} })
.ToDictionary(i => i.Key, i=>i.Value );

var part1Id01 = ((JObject) parts["part1"])["id-01"] ; // contextA

CodePudding user response:

In this case, I would recommend using a strongly typed class and System.Text.Json (or the serialization library of your choosing) to deserialize your object. You could create classes like the following:

public class MyClass
{
    [JsonPropertyName("series")]
    public string Series { get; set; }
    [JsonPropertyName("series_color")]
    public List<string> SeriesColor { get; set; }
    [JsonPropertyName("parts")]
    public Dictionary<string, PartsClass> Parts { get; set; }
}

public class PartsClass 
{
    [JsonPropertyName("id-01")]
    public string Id1 { get; set; }
    [JsonPropertyName("id-02")]
    public string Id2 { get; set; }
    [JsonPropertyName("id-03")]
    public string Id3 { get; set; }
}

And then you can use the serializer like this:

var serialized = JsonSerializer.Deserialize<MyClass>(message);

If the "PartsClass" is dynamic (I.E. you never know how many ids you might have) then you could make that another Dictionary<string, string>

  • Related