Home > Software engineering >  Deserializing custom JSON in C#
Deserializing custom JSON in C#

Time:10-27

I am attempting to deserilize some custom JSON into a Dictionary, but I'm having a hard time figuring out how to approach it. I've done it before having a Model class, but in this case, I need to do it in a specific way.

Here's what the Json looks like:

 {
     Values:
        {
          "Value1":"XXX",
          "value2" :
                 {
                       "SubValue1":"YX",
                       "SubValue2":"AB"
                 }
       }
}

The goal here would be to create a Dictionary<string,string> and populate it, so that:

    Key          Value
    Value1       XXX
    Value2       {
                   "SubValue1":"YX",
                   "SubValue2":"AB"
                 }   

Is there a quick way to get this deserilized like that? Any tips or hints on how to get this done easily?

CodePudding user response:

try this, I converterted your json to Dictionary<string,string>

var json = "{\"Values\":{\"Value1\":\"XXX\",\"value2\":{\"SubValue1\":\"YX\",\"SubValue2\":\"AB\"}}}";
var jsonDeserialized =  JsonConvert.DeserializeObject<Root>(json);

Dictionary<string,string>  dict = jsonDeserialized.Values.ToDictionary(i => i.Key, j => j.Value.ToString());

dict["value2"] = dict["value2"].Replace("\n", "").Replace("\r", "");

output

{
  "Value1": "XXX",
  "value2": "{\"SubValue1\":\"YX\",\"SubValue2\":\"AB\"}"
}

how to use

string value1 = dict["Value1"];
Value value2 = JsonConvert.DeserializeObject<Value>(dict["value2"]);
Values values = new Values { Value1=value1, Value2=value2 };

value1

XXX

value2

{
"SubValue1":"YX",
"SubValue2":"AB"
}

classes

public class Values
{
    public string Value1 {get; set;}
    public Value Value2 {get; set;}
}
public class Value
{
    public string SubValue1 { get; set; }
    public string SubValue2 { get; set; }
}
public class Root
{
    public Dictionary<string, Object> Values { get; set; }
}
  • Related