borewik
borewik

Reputation: 83

Take first element from dynamic JsonConvert.DeserializeObject array

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

Upvotes: 3

Views: 8037

Answers (4)

PinBack
PinBack

Reputation: 2564

Use the class RARAGA from Rahul's answer and convert the JToken (like ASpirin's answer):

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; }
}

JObject loObject = JObject.Parse(apiResult);
RARAGA loRARAGA = loObject["result"].First.First.ToObject<RARAGA>();
Console.WriteLine(loRARAGA.a[0]);

Upvotes: 0

ASpirin
ASpirin

Reputation: 3651

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

Upvotes: 4

Stanislav Rudnichenko
Stanislav Rudnichenko

Reputation: 144

Try this

result.result[0]["a"][0]

use result[0] instead result.RARAGA

Upvotes: 0

Rahul
Rahul

Reputation: 77896

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]

Upvotes: 1

Related Questions