Search code examples
c#jsondeserializationjavascriptserializer

How to deserialize and get the object and its array keys and values


I have the following JSON assigned to the variable strP:

{"get_the_data":[{"when_date":"09/12/2019","which_loc":"Orlando","who_witness":"visitor"}]}

And I need to generate the following output:

get_the_data:
    when_date - 09/12/2019
    which_loc - Orlando
    who_witness - visitor

How can I deserialize this JSON so as to get the KEY and the VALUE of each array within the object? Here is what I have tried so far:

string object1, string array1;
var jsonObj = new JavaScriptSerializer().Deserialize<RO>(strP);
//get the parent key: 'get_the_data'
object1 = get_the_data.ToString();
foreach (var p in strP._data)
{
    //how can I get the KEY and the VALUE of each array within the object
    array1 += p.Key + " - " + p.Value + Environment.NewLine; //e.g. when_date - 09/12/2019
}

Console.WriteLine(object1 + ":" + Environment.NewLine + array1);
//...
public class Data1
{
    public string when_date { get; set; }
    public string which_loc { get; set; }
    public string who_witness { get; set; }
}

public class RO
{
    public List<Data1> _data { get; set; }
}

p.s. I am wanting to avoid using external JSON library and use native C# methods.


Solution

  • If you're just looking to get the keys and values from the JSON without hardcoding the key names in advance, you can deserialize to a Dictionary<string, List<Dictionary<string, string>>>:

    var jsonObj = new JavaScriptSerializer().Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(strP);
    
    string indent = "   ";
    var sb = new StringBuilder();
    foreach (var outerPair in jsonObj)
    {
        sb.Append(outerPair.Key).AppendLine(":");
        outerPair.Value.SelectMany(d => d).Aggregate(sb, (s, p) => s.Append(indent).Append(p.Key).Append(" - ").AppendLine(p.Value));
    }
    
    Console.WriteLine(sb);
    

    Incidentally, your RO type cannot be used to deserialize the JSON shown in your question because the name of its property:

    public List<Data1> _data { get; set; }
    

    differs from the property name in the JSON:

    {"get_the_data":[ ... ] }
    

    These property names need to match since JavaScriptSerializer does not have built-in support for renaming of properties during (de)serialization. See here for details.