0

Recently I need to parse JSON object like this:

{
   "method":"someMehtod",
   "content":{"oneObject":"can be a very complicated object"},
   "somotherthing":"someOtherValue"
}

into C# with Newtonsoft JSON.NET. I know it is very common to create a new class or classes for the purpose but this is highly unwelcome choice to my current situation since it is considered unnecessary to my superior (and I don't want there to be too many classes like this either). Is there anything that resembles JAVA's JSONObject class in C# world I can use to query multiple level json without making new class?

HarryTheF
  • 299
  • 1
  • 4
  • 11
  • Tell your superior: 1. It is better to have classes since they are strongly typed. 2. What is the problem with having classes or many of them? 3. You do not need to write the classes manually--see [this answer](https://stackoverflow.com/a/42708158/4228458) 4. Once you deserialize you will want to process or do something with data, so working with objects of type `object` will be buggy. – CodingYoshi Nov 04 '17 at 15:46

2 Answers2

5

You can use JSON.Net's JObject. Here's an example:

var jsonString = "{\"method\":\"someMehtod\",   \"content\":{\"oneObject\":\"can be a very complicated object\"},   \"somotherthing\":\"someOtherValue\"}";
var obj = JsonConvert.DeserializeObject<JObject>(jsonString);
Console.WriteLine(obj["content"]["oneObject"]); // will print "can be a very complicated object"

dotnet fiddle demo available here

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
0

Take a look at the JsonConvert.DeserializeAnonymousType method. Define an anonymous type inline to define the expected structure and pass it in as a parameter. No new classes required, but I suspect if your superior is against creating new classes (really??) then they'll be against anonymous types too...

https://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm

pcdev
  • 2,852
  • 2
  • 23
  • 39
  • still need to create class of the same structure – Yogesh H Shenoy Nov 04 '17 at 15:27
  • Not sure if I can persuade him for this. Creating a class for this is a reasonable option but this adds up the complexity. And since there's only one place this structure will be used. (We are writing small app.) – HarryTheF Nov 04 '17 at 15:33
  • https://wtools.io/ will do it for you – jdmneon Jan 22 '22 at 22:30
  • create a class structure out of it, it has to be VALID JSON though, not all JSON being passed around on the internet meets the standard some people add their own little custom extensions for convenience – jdmneon Jan 22 '22 at 22:31