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.

2
  • 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. Commented Aug 19, 2015 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? Commented Aug 19, 2015 at 19:30

5 Answers 5

5

You can use the dynamic keyword

dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.unashamedohio.summonerLevel);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this work quite ok. Might have to read more about dynamic objects. Thanks to all btw
I really like dynamic and there are situations where using it it's the only solution, but IMO it should be use with caution.
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.

Comments

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["test"] as JObject;
int lolSummorLvl = (int) innerObj["summonerLevel"];

2 Comments

Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string,dynamic>' to 'Newtonsoft.Json.Linq.JObject'2013\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs. Thats the error im getting in the Jobject obj line
sounds like your json is stored in a dictionary, not a string.
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();
                 
                }
            }

Comments

0

With .NET 8 the easiest method I've found is using JsonSeralizer.Deserialize. This works similarly to using dynamic DeserializeObject on older versions.

Example to get id, sys_id and name from JSON:

            JsonObject? _departmentJson = JsonSerializer.Deserialize<JsonObject>(deparmentCallResult)!;

            _departmentID = (string)_departmentJson["result"]!["id"]!; 
            _department_sys_ID = (string)_departmentJson["result"]!["sys_id"]!; 
            _department_Name = (string)_departmentJson["result"]!["name"]!;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.