3
"inputs": {
    "input1": {
        "value": "abc"
    },
    "input2": {
        "value": "cde"
    },
    "input3": {
        "value": "efg"
    },
    "input4": {
        "value": "ghi"
    },      
}

Here number of properties in "inputs" may vary. How can I deserialize this into class:

class Inputs
{
    public Input[] Values{get; set;}
}

class Input
{
    public string input {get; set;}
}

One option is to change the json "inputs" as an array, but I dont have that choice now

maccettura
  • 10,514
  • 3
  • 28
  • 35
TheCoder
  • 49
  • 1
  • 8
  • Is your JSON _exactly_ that? Where `input1`, `input2`, etc are dynamic and could have any number of inputs? – maccettura Sep 11 '18 at 17:30
  • @maccettura, unfortunately, yes – TheCoder Sep 12 '18 at 05:31
  • Also a duplicate of [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/a/24536564/3744182) or [Deserialize nested JSON into C# objects](https://stackoverflow.com/a/38793347/3744182). – dbc Sep 12 '18 at 23:31

2 Answers2

4

Your data matches the following data structure.

public class Data
{
    public Dictionary<string, Dictionary<string, string>> Inputs { get; set; }
}

Since you have not mentioned using any library for de/serializing JSON objects, I suggest pretty famous NewtonSoft library for .Net framework.

In you case you can simply deserialize your data with the following snippet.

var data = JsonConvert.DeserializeObject<Data>(YOUR_JSON_STRING);
Hasan Emrah Süngü
  • 3,488
  • 1
  • 15
  • 33
-1

How to install

Install-Package Newtonsoft.Json:

In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the figure:

enter image description here

Then create class with input parameters that you expect to get it as a JSON response.

public class Inputs
{
    public string input1 { get; set; }
    public string input2 { get; set; }
    public string input3 { get; set; }
    public string input4 { get; set; }
}

Now we will convert it to a .NET object using DeserializeObject() method of JsonConvert class. Here is the code:

private void JSONDeserilaize(string json)
{
    var obj = JsonConvert.DeserializeObject<Inputs>(json);
}

Now you have an object of type Inputs Deserialized successfully

Di Kamal
  • 173
  • 13