SwethaD SwethaD - 4 months ago 10
JSON Question

Deserialize a json string in specific format

I am trying to deserialize the JSON string below:

[{"Code1":"AA","Code2":"AB"},{"Code1":"BB","Code2":"BC"},
{"Code1":"A1","Code2":"A12"},{"Code1":"A2","Code2":"A23"},
{"Code1":"A4","Code2":"A45"},{"Code1":"A3","COde2":"A45"}]


into the following format:

{"Header":["Code1","Code2"], "Values":[["AA","AB"],["BB","BC"],["A1","A12"],["A2","A23"],["A4","A45"],["A3","A45"]]}


I am trying to deserialize using
JsonConvert.DeseriaizeObject()
. I am not able to achieve the desired format.

Answer

Ah, so you have a collection of identically structured objects, and want to convert it to something akin to a CSV table (sequence of headers, then sequence of records)?

You can convert from the objects collection format to records table format using the following method:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

//other code, class declaration etc. goes here

string ObjectsToTable(string collectionJson)
{
    // reading the collection from passed JSON string
    JArray collection = JArray.Parse(collectionJson);

    // retrieving header as a list of properties from the first element
    // it is assumed all other elements have the exact same properties
    List<string> header = (collection.First as JObject).Properties().Select(p => p.Name).ToList();

    // retrieving values as lists of strings
    // each string is corresponding to the property named in the header
    List<List<string>> values = values = collection.Children<JObject>().Select( o => header.Select(p => o[p].ToString()).ToList() ).ToList();

    // passing the table structure with the header and values
    return JsonConvert.SerializeObject(new { Header = header, Values = values });
}