Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take first element from dynamic JsonConvert.DeserializeObject array

Tags:

json

c#

I have json string output like that:

string apiResult =

{
   "error":[],
   "result":{
      "RARAGA":{
         "a":["4","1","1.1"],
         "b":["4","1","2"],
         "c":["1","2"],
         "v":["4","4"],
         "p":["5","2"],
         "t":[1],
         "l":["3","4"],
         "h":["5","7"],
         "o":"8"
      }
   }
}

What I'm trying to do is to convert it with Newtonsoft.Json:

dynamic result = JsonConvert.DeserializeObject(apiResult);

to only take this result of "RARAGA" property as an object so I can take its values a/b/c etc. I just need to take it's values like:

result.result.RARAGA.a[0]

Point is this string "RARAGA" is always random

like image 536
borewik Avatar asked Dec 03 '25 23:12

borewik


2 Answers

In case you don't know what is the name of property (or want to iterate all properties) you can use JObject

JObject result = JsonConvert.DeserializeObject<JObject>(apiResult);
dynamic res = result["result"].First().First;

res will contains a value of first object as a dynamic variable

like image 93
ASpirin Avatar answered Dec 05 '25 13:12

ASpirin


If you use http://json2csharp.com/# then below should be the model you should deserialize your json string to

public class RARAGA
{
    public List<string> a { get; set; }
    public List<string> b { get; set; }
    public List<string> c { get; set; }
    public List<string> v { get; set; }
    public List<string> p { get; set; }
    public List<int> t { get; set; }
    public List<string> l { get; set; }
    public List<string> h { get; set; }
    public string o { get; set; }
}

public class Result
{
    public RARAGA RARAGA { get; set; }
}

public class RootObject
{
    public List<object> error { get; set; }
    public Result result { get; set; }
}

So your deserialization would become

RootObject result = JsonConvert.DeserializeObject<RootObject>(apiResult);

Then you can access it like

result.result.RARAGA.a[0]
like image 29
Rahul Avatar answered Dec 05 '25 13:12

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!