0

I want to create a method with the C# Newtonsoft library that can take in a parameter value to return the JSON data value, without needing to know and create a class beforehand, but all I can find are examples to deserialise into a class or into a dynamic object, both needing to know JSON structure prior at development time

Here's an example of what the kind of JSON format I'm expecting, but is subject to change:

{
  "Input":
  [
    {
      "Name": "foo"
    },
    {
      "Name": "bar"
    },
  ]
  "Output":
  [
    {
      "Name": "bob"
    },
    {
      "Name": "builder"
    },
  ]
}

I'm locked into using Newtonsoft library to work on the JSON file, or do it myself from scratch as it's an embedded system.

1
  • Look at JTokenReader Commented Feb 13, 2020 at 12:32

1 Answer 1

1

You can use JObject. If you deserialize a class without the type it will be deserialized to JObject. You would access your JObject values with named index which is obviously your property name. Other type of interest to you is JArray. This all resides in namespaces:

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

Example:

So the example with your JSON would be:
var json = @"{
  ""Input"":
  [
    { ""Name"": ""foo"" },
    { ""Name"": ""bar"" }
  ],
  ""Output"":
  [
    { ""Name"": ""bob"" },
    {""Name"": ""builder""}
  ]
}";

var obj = JsonConvert.DeserializeObject(json) as JObject;
var input = obj["Input"] as JArray;
var inputArray = input[0]["Name"];

This would get the first element in array that is in Input field - "foo".

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

1 Comment

Thank you! A lot of people posting in other threads missed the key thing about what namespaces to use, in my case I didn't know I needed "Newtonsoft.Json.Linq" to use JObject, so glad you added that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.