Home > Blockchain >  JSON Deserialize with change name field
JSON Deserialize with change name field

Time:08-29

I need to deserialize this json: { "name": { "field": "kop", "field2": false } }

But "Name" is already different, how I can do it? For example: one time it can be

{ "JOHN": { "field": "kop", "field2": false } }

, but another time it will be another name:

{ "BILL": { "field": "kop", "field2": false } } etc.

CodePudding user response:

You need to use a dictionary:

Dictionary<string, MyData>

Like this:

    public class MyData
    {
        [JsonProperty("field")]
        public string Field { get; set; }

        [JsonProperty("field2")]
        public bool Field2 { get; set; }
    }

Then deserialize like this:

var result = JsonConvert.DeserializeObject<Dictionary<string, MyData>>(jsonStringGoesHere);

So now the name will become the Key of the dictionary.

You need to use Newtonsoft Json.

You can get the data out like this:

var myData = result["JOHN"];

Or you can get the data like this:

var myData = result.Values.ToList()[0];

or you can get the KeyValuePair like this:

var keyValPair = result.FirstOrDefault();

Which then you can use the Key and Value properties to get both key and value. You will need to add using System.Linq to call FirstOrDefault()

CodePudding user response:

you can use Newtonsoft.Json

using Newtonsoft.Json;

   var jsonParsed = JObject.Parse(json).Properties().First();

    Data data = new Data
    {
        Name = jsonParsed.Name,
        Value = jsonParsed.Value.ToObject<Item>()
    };

public partial class Data
{
    public string Name { get; set; }

    public Item Value { get; set; }
}

public partial class Item
{
    [JsonProperty("field")]
    public string Field { get; set; }

    [JsonProperty("field2")]
    public bool Field2 { get; set; }
}

  • Related