i can't figure out how to create a JSONProperty with any number. For example my JSON that i receive looks like this from the start:
{ "255710": { "success": true,...
The specific Problem that i have is, that the first number, in this case 255710, can be any random number. Therefore i can not deserialize it so easily.
I have tried it with:
[JsonProperty("*")] [JsonProperty()] and [JsonProperty("")]
but i'm running out of ideas here.
Is there any smart solution for this problem? Im thankfull for every help.
CodePudding user response:
try this
var json ="{ \"255710\": { \"success\": true}}";
var dict=JsonConvert.DeserializeObject<Dictionary<string,SuccessClass>>(json);
public class SuccessClass
{
[JsonProperty("success")]
public bool Success {get; set;}
}
how to use
var success=dict["255710"].Success; // true
or you can use int if you like it more
var dict=JsonConvert.DeserializeObject<Dictionary<int,SuccessClass>>(json);
var success=dict[255710].Success; //true
or if you don't know a key name
var key=dict.Keys.First();
var success=dict[key].Success; // true
// or if you don't need a key
var successObj=dict.Values.First(); //the whole sucess class
var success=dict.Values.First().Success; //true
CodePudding user response:
There are a few ways to parse this JSON. One way is to use JObject and skip the first element then, for convenience, convert to dynamic as follows:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
string json = "{ \"123\": { \"success\": true, \"other\": \"the string\" } }";
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
var dyn = obj.First.First.ToObject<dynamic>();
Console.WriteLine($"dyn.success: {dyn.success}");
Console.WriteLine($"dyn.other: {dyn.other}");
This will output:
dyn.success: True
dyn.other: the string
I've skipped the first element since it's random, but you should ask yourself if it is really random. Isn't it an id for a method call? If it is, then you can more easily convert it into a dictionary and just read the key with the ID.
And you may also use a strong typed class for the result if it is known to you.