17

From the result of an API call I have a large amount of JSON to process.

I currently have this

Object convertObj = JsonConvert.DeserializeObject(responseFromServer);

I am aware that I could do something like

Movie m = JsonConvert.DeserializeObject<Movie>(responseFromServer);

And then use it like

m.FieldName
m.AnotherField
//etc

Ideally I would like to do something like

var itemName = convertObj["Name"];

to get the first Name value for the first item in the list.

Is this possible, or do I have to create a class to deserialize to?

The reason I do not want to create the class is I am not the owner of the API and the field structure may change.

Edit.

Okay so I created the class as it seems the best approach, but is there a way to deserialize the JSON into a list?

var sessionScans = new List<SessionScan>();
sessionScans = JsonConvert.DeserializeObject<SessionScan>(responseFromServer);

Complains that it cannot convert SessionScan to generic list.

6
  • u can use Dynamic but it is not recommended. Commented Nov 22, 2016 at 4:30
  • Possible duplicate of Deserialize JSON into C# dynamic object? Commented Nov 22, 2016 at 4:32
  • @MohitShrivastava why is it not recommended ? Commented Nov 22, 2016 at 4:49
  • Possible duplicate of Deserialize json object into dynamic object using Json.net Commented Nov 22, 2016 at 4:54
  • 1
    @MohitShrivastava yes I agree completely with you. On the other side, the question essentially is Deserializing JSON response without creating a class. Commented Nov 22, 2016 at 4:59

7 Answers 7

22

No need to use dynamic, you can simply use JToken which already does what you expect:

var json = @"
    {
        ""someObj"": 5
    }
";
var result = JsonConvert.DeserializeObject<JToken>(json);
var t = result["someObj"]; //contains 5
Sign up to request clarification or add additional context in comments.

Comments

14

With .NET 6, this can be done as below,

using System.Text.Json;
using System.Text.Json.Nodes;

string jsonString = @"some json string here";

JsonNode forecastNode = JsonNode.Parse(jsonString)!;

int temperatureInt = (int)forecastNode!["Temperature"]!;
Console.WriteLine($"Value={temperatureInt}");

//for nested elements, you can access as below
int someVal = someNode!["someParent"]["childId"]!.ToString();

Refer this MS docs page for more samples - create object using initializers, make changes to DOM, deserialize subsection of a JSON payload.

1 Comment

Check out the new improvements in .NET 8 for System.Text.Json, it is much better now.
5

You can try with JObject.Parse :

dynamic convertObj = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = convertObj.Name;
string address = convertObj.Address.City;

Comments

2

The below example can deserialize JSON to a list of anonymous objects using NewtonSoft.Json's DeserializeAnonymousType method.

var json = System.IO.File.ReadAllText(@"C:\TestJSONFiles\yourJSONFile.json");
var fooDefinition = new { FieldName = "", AnotherField = 0 }; // type with fields of string, int
var fooListDefinition = new []{ fooDefinition }.ToList();

var foos = JsonConvert.DeserializeAnonymousType(json, fooListDefinition);

Comments

1

I had this problem working with unknown APIs then I decide to come over this problem using this approach, I'm writing down here my test case:

            [TestMethod]
        public void JsonDocumentDeserialize()
        {
            string jsonResult = @"{
""status"": ""INTERNAL_SERVER_ERROR"",
    ""timestamp"": ""09-09-2019 11:00:24"",
    ""message"": ""documentUri is required.""
}";

            var jDoc = JsonDocument.Parse(jsonResult);
            if (jDoc.RootElement.TryGetProperty("message", out JsonElement message))
            {
                Assert.IsTrue(message.GetString() == "documentUri is required.");
            }
        }

it worked for me because first I was looking to find a way to use dynamic type as it's mentioned in Azure Function HTTPTrigger. But I found this approach most useful and robust.

Microsoft Reference

Comments

0

You can use Json.NET's LINQ to JSON API

JObject o = JObject.Parse(jsonString);
string prop = (string)o["prop"];

Comments

0

Use Newtonsoft.Json

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

var json = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]";
var ja = (JArray)JsonConvert.DeserializeObject(json);
var jo = (JObject) ja[0];
Console.WriteLine(jo["a"]);

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.