1

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?

1
  • 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 4. Once you deserialize you will want to process or do something with data, so working with objects of type object will be buggy. Commented Nov 4, 2017 at 15:46

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

still need to create class of the same structure
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.)
wtools.io will do it for you
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

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.