Stuart Brant
Stuart Brant

Reputation: 155

Manipulation multidimensional JSON array in C#

I need to manipulate the following JSON Array to compare the value for Company Id. Any suggestions how I can manipulate this.

{  "39513447": {    "field": "39513447",    "label": "CompanyId",    "type": "number",    "value": "5907"  },  "39513458": {    "field": "39513458",    "label": "UserId",    "type": "number",    "value": "5904"  },  "39380671": {    "field": "39380671",    "label": "Name",    "type": "name",    "value": "first = First\nlast = Name"  },  "39380675": {    "field": "39380675",    "label": "Company Name",    "type": "text",    "value": "CompanyName"  },  "39381333": {    "field": "39381333",    "label": "Planned Gross Salary Amount",    "type": "number",    "value": "11020"  },  "39381266": {    "field": "39381266",    "label": "Per:",    "type": "select",    "value": "Annum"  },  "39380485": {    "field": "39380485",    "label": "Planned Gross Dividend Amount",    "type": "number",    "value": "31980"  },  "39381357": {    "field": "39381357",    "label": "Per:",    "type": "select",    "value": "Annum"  }}

I have a class with these 3 properties:

public int id { get; set; }
public DateTime timestamp { get; set; }
public object data { get; set; }

Which I deserialize using:

T jsonObject = JsonConvert.DeserializeObject<T>(text);

Ideally want to deserialize into class with these 4 properties:

public string field { get; set; }
public string label { get; set; }
public string type { get; set; }
public string value { get; set; }

Upvotes: 0

Views: 430

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29846

Create a class:

public class MyClass
{
    public string field { get; set; }
    public string label { get; set; }
    public string type { get; set; }
    public string value { get; set; }
}

And simple deserialize your json into a Dictionary:

var json = GetJsonString();
var dict = JsonConvert.DeserializeObject<Dictionary<int,MyClass>>(json);

Here's how to fetch data:

var curr = dict[39513447]; 
var field = curr.field;
var label = curr.label;
// etc.

Upvotes: 1

Related Questions