Home > database >  How to parse json array that has objects with numeric key in ASP.NET?
How to parse json array that has objects with numeric key in ASP.NET?

Time:03-29

I'm developing an ASP.NET application. I get JSON array from the client in the following format:

[ {“1”: “value1”}, {“5”: “value2”}, {“10”: “value32”} ]

I want to save this array in the database as the array of following entity:

class Entry
{

public int Code { get; set; }

public string Value { get; set; } 
}

How to convert this JSON array to the array of the entries?

CodePudding user response:

Simplest thing is perhaps to use a Dictionary as an interim:

//Newtonsoft. For System.Text.Json change  JsonConvert.DeserializeObject -> JsonSerializer.Deserialize

JsonConvert.DeserializeObject<Dictionary<int,string>[]>(yourJson)
  .Select(d => Entry.FromKeyValuePair(d.First()));

Your Entry class will need a helper method:

public static Entry FromKeyValuePair(KeyValuePair<int,string> kvp) => new Entry{ Code = kvp.Key, Value = kvp.Value };

Or you can put that logic in the Select..

The result of the Select will be an IEnumerable<Entry>; you can do further operations on it like foreach'ing it etc: https://dotnetfiddle.net/pzMrI6

It looks (from your use of an int property for Code) that you expect the key to always be ints but if they ever are not, you'll need to switch to Dictionary<string,string>(and the same for the key value pair in the static method) and handle parsing it yourself somehow

CodePudding user response:

You json is incorrect. It must be something like this:

[   {"Code":1, "Value": "value1"},   {"Code":5, "Value": "value2"},   {"Code":10, "Value": "value32"} ]

Then you can serialize it using the following code:

using System.Text.Json;

var json = "[   {\"Code\":1, \"Value\": \"value1\"},   {\"Code\":5, \"Value\": \"value2\"},   {\"Code\":10, \"Value\": \"value32\"} ]";
var test = JsonSerializer.Deserialize<Entry[]>(json);
Console.WriteLine(test);

internal class Entry { public int Code { get; set; } public string Value { get; set; } }

CodePudding user response:

Your JSON is an array with a set of dictionaries.

  1. Deserialize as List<Dictionary<string, string>>.

  2. Data Transformation.

    2.1 Flatten the result from 1 to Dictionary<string, string>.

    2.2 Cast Dictionary<string, string> to List<Entry> with assume the key is integer.

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;

List<Dictionary<string, string>> dict = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
List<Entry> entries = dict
    .SelectMany(x => x)
    .Select(x => new Entry
    {
        Code = Int32.Parse(x.Key),
        Value = x.Value
    })
    .ToList();

Sample Program

CodePudding user response:

json to class : (use _ to make number to key)

 public class Root
{
    public string _1 { get; set; }
    public string _5 { get; set; }
    public string _10 { get; set; }
}

Deserialize:

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
  • Related