1

I have this json:

{
    "test": 
        {
            "id": 107537,
            "name": "test",
            "profileIconId": 785,
            "revisionDate": 1439997758000,
            "summonerLevel": 30
        }
}

I want to get the field named summonerLevel.

I have tried to convert this json to a string and then search for summonerLevel, but I know that this solution is not okay.

I'm using Json.NET.

r0t.algo r
  • 25
  • 1
  • 1
  • 7
  • 2
    There are *lots* of questions on Stack Overflow about parsing JSON. You could parse it to an object where you've created an appropriate class beforehand, or use Json.NET's "LINQ to JSON", or any number of things. Please show what you've tried so far. – Jon Skeet Aug 19 '15 at 18:56
  • You can search in the string. The other alternative might be to deserialize to another object with only the data you care about, but that's not a great idea either. Is there any reason you can't deserialize the JSON into a whole object, then just check the value on the object? – Mathieson Aug 19 '15 at 19:30

4 Answers4

5

You can use the dynamic keyword

dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.unashamedohio.summonerLevel);
Eser
  • 12,346
  • 1
  • 22
  • 32
1

I'm assuming this json is stored in a string, let's say called json... so try

string json = "...";
JObject obj = JsonConvert.DeserializeObject<JObject>(json);
JObject innerObj = obj["unashamedohio"] as JObject;
int lolSummorLvl = (int) innerObj["summonerLevel"];
Aaron
  • 1,390
  • 1
  • 16
  • 30
  • Cannot implicitly convert type 'System.Collections.Generic.Dictionary' to 'Newtonsoft.Json.Linq.JObject'2013\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs. Thats the error im getting in the Jobject obj line – r0t.algo r Aug 19 '15 at 19:20
  • sounds like your json is stored in a dictionary, not a string. – Aaron Oct 03 '17 at 19:28
1

You have a couple of possibilities (as already showed in the other answers). Another possibility would be to use the JObject and JProperty properties provided from Json.Net, in order to directly fetch the value like this:

var jsonObject = (JObject)JsonConvert.DeserializeObject(json);
var unashamedohio = (JObject)(jsonObject.Property("unashamedohio").Value);
var summonerLevel = unashamedohio.Property("summonerLevel");
Console.WriteLine(summonerLevel.Value);

Yet another possibility would be to create a typed model of the JSON structure:

public class AnonymousClass
{
    public UnashamedOhio unashamedohio { get; set; }    
}

public class UnashamedOhio
{
    public int summonerLevel { get; set; }
}

and use it to retrieve the value:

var ao = JsonConvert.DeserializeObject<AnonymousClass>(json);
Console.WriteLine(ao.unashamedohio.summonerLevel);

Both solutions print the same value: 30.

IMO you should use always typed models when possible and if you do a lot of value fetching from a JSON structures. It provides error checking in the IDE (as opposed to dynamic) which pay-offs at runtime.

keenthinker
  • 7,645
  • 2
  • 35
  • 45
0

This worked for me

Found here - How do you read a simple value out of some json using System.Text.Json?

var jsonResult = JsonSerializer.Deserialize<JsonElement>(apiResponse).GetProperty("collection");
                        return jsonResult.EnumerateArray();

Code with HTTPCLient GET:

            using (var httpClient = new HttpClient())
            {
                // Headers
                httpClient.DefaultRequestHeaders.Add("X-AppSecretToken", "sJkvd4hgr45hhkidf");
                httpClient.DefaultRequestHeaders.Add("X-AgreementGrantToken", "r55yhhsJkved4ygrg5hssdhkidf");

                using (var response = await httpClient.GetAsync("https://restapi/customers"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync(); // Result

                    var jsonResult = JsonSerializer.Deserialize<JsonElement>(apiResponse).GetProperty("collection");
                    return jsonResult.EnumerateArray();
                 
                }
            }
Stefan27
  • 845
  • 8
  • 19