-1

On .NET 4.5 I was getting by

string respString= response.Body; // { "name":"John", "age":30, "car":null}
var respObj= JsonConvert.DeserializeObject<dynamic>(respString);

In this case, I was able to create a dynamic object of each property.

However, I have dropped to .NET 3.5, and the dynamic option is not available. How can I get each property as

string gottenName= respObj.name;
double gottenAge = respObj.age; 

etc.

Thank you guys kindly!

ali.vic
  • 11
  • 4
  • If you know what the data contract is like ahead of time why use `dynamic`? –  Jun 26 '20 at 02:37
  • Does this answer your question? [Deserialize json object into dynamic object using Json.net](https://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net) – Pavel Anikhouski Jun 26 '20 at 06:59

2 Answers2

1

Visit a JSON to C# class conversion service, eg: https://www.jsonutils.com/

Paste in the JSON:

{ "name":"John", "age":30, "car":null}

It will generate a Class:

public class Example
{
    public string name { get; set; }
    public int age { get; set; }
    public object car { get; set; }
}

Then you don't need dynamic:

Example respObj= JsonConvert.DeserializeObject<Example>(respString);
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • You mean manually go to the site and input the string? – ali.vic Jun 26 '20 at 03:06
  • In order to generate the Class unless you want to write it yourself. – Jeremy Thompson Jun 26 '20 at 03:07
  • the problem is that I want to create it from the Json itself. not hard code a get and setter to a json that might change – ali.vic Jun 26 '20 at 03:21
  • I'm even ok with parsing the string, but was looking for something else – ali.vic Jun 26 '20 at 03:22
  • The closest you will get is AnonTypes using Linq (but alas no extension for JSON, only objects, XML and SQL) and without Dynamic you will have to parse the JSON as a string yourself. The JSON format shouldn't change much and there's a trick where if you only need Name and Age fields (and the other data changes) that's OK it will still deserialise. My real concern is why .Net 3.5? The solution would be to upgrade all the products to .Net 4.6 or above. – Jeremy Thompson Jun 26 '20 at 03:26
0

You can also parse to C# object using newtonsoft.dll

code will be

  JObject jsonResponse = JObject.Parse(respString);
   //you can access name value using 
  var nameValue=  (string)jsonResponse["name"]
   //respString is jsonstring
Shyam sundar shah
  • 2,473
  • 1
  • 25
  • 40