2

I got below data as JSON Objects:

{"Data1":
    {"id":1,
     "last":"0.00000045"},
"Data2":
    {"id":2,
     "last": "0.02351880"}}

What is the best way in c# to convert it to below JSON Array:

[{"name":"Data1",
     "id":1,
     "last":"0.00000045"},
    {"name":"Data2",
     "id":2,
     "last": "0.02351880"}]

Thanks in advance,

iziz1

iziz1
  • 23
  • 4
  • You can find many ways in this link or related searchs. [Json Converstation](https://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object) – Murat Can OĞUZHAN Jan 01 '18 at 14:38

2 Answers2

3

You can try following codes;

Firstly, create model classes for deserialization

public class Data
{
    public int id { get; set; }
    public string last { get; set; }
}

public class DataWithKey
{
    public string name { get; set; }
    public int id { get; set; }
    public string last { get; set; }
}

Then deserialize the original Json as Dictionary<string, Data> and convert to desired list; (Requires Json.NET)

var dataAsList = JsonConvert.DeserializeObject<Dictionary<string, Data>>(json).Select(x => new DataWithKey
{
    name = x.Key,
    id = x.Value.id,
    last = x.Value.last
}).ToList();
var convertedJson = JsonConvert.SerializeObject(dataAsList); //Desired json

Output:

[
   {
      "name":"Data1",
      "id":1,
      "last":"0.00000045"
   },
   {
      "name":"Data2",
      "id":2,
      "last":"0.02351880"
   }
]
lucky
  • 12,734
  • 4
  • 24
  • 46
0

Use the DataContractJsonSerializer class to serialize and deserialize json data.

Eugene
  • 10,957
  • 20
  • 69
  • 97