andrewb
andrewb

Reputation: 3095

Deserializing JSON response without creating a class

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.

Upvotes: 17

Views: 37722

Answers (7)

Rob
Rob

Reputation: 27357

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

Upvotes: 22

Anand Sowmithiran
Anand Sowmithiran

Reputation: 2920

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.

Upvotes: 14

Ash K
Ash K

Reputation: 3651

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

Upvotes: 2

Nader Vaghari
Nader Vaghari

Reputation: 171

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

Upvotes: 1

GlitterX
GlitterX

Reputation: 16

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"]);

Upvotes: 0

Frank Fajardo
Frank Fajardo

Reputation: 7359

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

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

Upvotes: 0

Yanga
Yanga

Reputation: 3012

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;

Upvotes: 5

Related Questions