Getting stuck reading JSON Children using Newtonsoft.json - c#

I'm having problems reading Children of the root element and understanding where I'm going wrong in the JSON below:
{
"001": {
"peers": [
{
"id": 0,
"server": "1.1.1.1:80",
"name": "1.1.1.1:80",
"backup": false,
"weight": 1,
"state": "up",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
},
{
"id": 1,
"server": "127.0.0.1:8888",
"name": "127.0.0.1:8888",
"backup": false,
"weight": 1,
"state": "down",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
}
],
"keepalive": 0,
"zombies": 0,
"zone": "001"
},
"002": {
"peers": [
{
"id": 0,
"server": "1.1.1.2:80",
"name": "1.1.1.2:80",
"backup": false,
"weight": 1,
"state": "up",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
},
{
"id": 1,
"server": "127.0.0.1:8888",
"name": "127.0.0.1:8888",
"backup": false,
"weight": 1,
"state": "down",
"active": 0,
"requests": 0,
"responses": {
"1xx": 0,
"2xx": 0,
"3xx": 0,
"4xx": 0,
"5xx": 0,
"total": 0
},
"sent": 0,
"received": 0,
"fails": 0,
"unavail": 0,
"health_checks": {
"checks": 0,
"fails": 0,
"unhealthy": 0
},
"downtime": 0
}
],
"keepalive": 0,
"zombies": 0,
"zone": "002"
}
}
I know I can pass the JSON into a JObject and find the server value below by naming the 001 JSON object:
JObject obj = JObject.Parse(jsonResponse);
var h = obj.Value<JObject>("001").Value<JArray>("peers")[0].SelectToken("server").ToString();
However I'd like to read the children of the root element (which I think are objects 001 and 002) regardless of their names, foreach through them to find values for the keys "zone" and "keepalive". I thought I could do this:
List<JToken> toks = obj.Root.Children().ToList<JToken>();
string output = "";
foreach (JToken token in toks)
{
JProperty prop = (JProperty)token;
output += prop.Value<string>("zone"); // returns nothing
string bla = token.ToString(); //returns 001 and all it's child objects
}
But the output string is blank. I can see that if I try token.ToString() the JToken object has stuff in it, but I can't seem to read it.
If I use Visual studio to create an object for Deserialization I get this for the root object which confuses me further:
public class Rootobject
{
public 001 001 { get; set; }
public 002 002 { get; set; }
}
What am I doing wrong? Any help would be greatly appreciated.
Jon

If you're trying to parse this JSON using JTokens, you need to understand the different kinds of possible tokens and the relationships between them. You would probably benefit from reading this answer.
At the root you have an object; this object has two properties called "001" and "002". Those properties' respective values are objects again, containing their own properties ("peers", "keepalive", "zombies" and "zone"). And so on.
If you ultimately want to loop through the root properties without knowing their names and then dump out the values of "zone" and "keepalive" properties of the child objects, you can do it like this:
var obj = JObject.Parse(json);
foreach (JProperty prop in obj.Properties())
{
var item = (JObject)prop.Value;
var zone = (string)item["zone"];
var keepalive = (int)item["keepalive"];
Console.WriteLine($"Zone: {zone} keepalive: {keepalive}");
}
Fiddle: https://dotnetfiddle.net/tNut9v
If JTokens make your head spin, then you might be better off declaring classes for the JSON. The only wrinkle is the dynamic property names in the root ("001", "002"). But you can handle that by deserializing to a Dictionary<string, T> where T is an Item class as shown below. Define the classes like this:
public class Item
{
public List<Peer> peers { get; set; }
public int keepalive { get; set; }
public int zombies { get; set; }
public string zone { get; set; }
}
public class Peer
{
public int id { get; set; }
public string server { get; set; }
public string name { get; set; }
public bool backup { get; set; }
public int weight { get; set; }
public string state { get; set; }
public int active { get; set; }
public int requests { get; set; }
public Responses responses { get; set; }
public int sent { get; set; }
public int received { get; set; }
public int fails { get; set; }
public int unavail { get; set; }
public HealthChecks health_checks { get; set; }
public int downtime { get; set; }
}
public class Responses
{
[JsonProperty("1xx")]
public int code_1xx { get; set; }
[JsonProperty("2xx")]
public int code_2xx { get; set; }
[JsonProperty("3xx")]
public int code_3xx { get; set; }
[JsonProperty("4xx")]
public int code_4xx { get; set; }
[JsonProperty("5xx")]
public int code_5xx { get; set; }
public int total { get; set; }
}
public class HealthChecks
{
public int checks { get; set; }
public int fails { get; set; }
public int unhealthy { get; set; }
}
Then you can deserialize and dump out the data you want like this:
var dict = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
foreach (var kvp in dict)
{
Item item = kvp.Value;
Console.WriteLine($"Zone: {item.zone} keepalive: {item.keepalive}");
}
Fiddle: https://dotnetfiddle.net/3rRmxJ

Related

Deserialize nested JSON into C# Object

I am getting the following response from an API
"results": {
"wan1": {
"id": "wan1",
"name": "wan1",
"alias": "",
"mac": "00:00:00:00:00:00",
"ip": "102.165.223.199",
"mask": 24,
"link": true,
"speed": 1000.0,
"duplex": 1,
"tx_packets": 501850173,
"rx_packets": 307154377,
"tx_bytes": 442319826490,
"rx_bytes": 234140958061,
"tx_errors": 0,
"rx_errors": 0
},
"dmz": {
"id": "dmz",
"name": "dmz",
"alias": "",
"mac": "00:00:00:00:00:00",
"ip": "10.10.10.1",
"mask": 24,
"link": false,
"speed": 0.0,
"duplex": 0,
"tx_packets": 0,
"rx_packets": 0,
"tx_bytes": 0,
"rx_bytes": 0,
"tx_errors": 0,
"rx_errors": 0
},
"internal1": {
"id": "internal1",
"name": "internal1",
"alias": "",
"mac": "00:00:00:00:00:00",
"ip": "0.0.0.0",
"mask": 0,
"link": false,
"speed": 0.0,
"duplex": 0,
"tx_packets": 0,
"rx_packets": 0,
"tx_bytes": 0,
"rx_bytes": 0,
"tx_errors": 0,
"rx_errors": 0
}
},
"vdom": "root",
}
I have tried a few approaches to representing this JSON in c# objects
{
public Dictionary<string, List<Result>> Result { get; set; }
}
public class Result
{
public string name { get; set; }
public string ip { get; set; }
public int tx_bytes { get; set; }
public int rx_bytes { get; set; }
}
And here is the method I am using to deserialize the JSON:
var result = await client.Request()
.AppendPathSegment("api/v2/monitor/system/interface")
.SetQueryParam("access_token", token)
.GetJsonAsync<InterfaceResponse>(cancellationToken: cancellationToken);
It should be simple, but for some reason, I can't figure out the correct object representation, but when I debug I am getting null
Thanks for the help.
I can see 2 issues:
It's "results" not "result".
"results" looks like Dictionary<string, Result> not Dictionary<string, List<Result>>.
Additionally, if you're using System.Text.Json then casing may matter depending on your settings.
try this
var jsonParsed = JObject.Parse(json);
Dictionary<string,Result> results = jsonParsed["results"]
.ToObject<Dictionary<string,Result>>();
string vdom = (string)jsonParsed["vdom"];
public class Result
{
public string name { get; set; }
public string ip { get; set; }
public long tx_bytes { get; set; }
public long rx_bytes { get; set; }
//another properties
}
You need to fix the classes:
public class InterfaceResponse
{
// 1. rename or use attributes
// 2. fix type from Dictionary<string, List<Result>>
public Dictionary<string, Result> results { get; set; }
}
public class Result
{
public string name { get; set; }
public string ip { get; set; }
public long tx_bytes { get; set; } // use long, some of the values are too big to fit int
public long rx_bytes { get; set; } // use long, some of the values are too big to fit int
}

Get all the values from JSON based on keyname

I got JSON from some process as following:
{
"Nodename": "Host1",
"OperatingSystem": "OS",
"Release": "3.6.2.1",
"Stats": [{
"Timestamp": "11/18/2021 18:31:58",
"Processes": [{
"Timestamp": "11/18/2021 18:31:58",
"Processname": "process1",
"CpuPercent": 0,
"MemoryPercent": 0.16,
}, {
"Timestamp": "11/18/2021 18:31:58",
"Processname": "process2",
"CpuPercent": 0,
"MemoryPercent": 0.46,
}, {
"Timestamp": "11/18/2021 18:31:58",
"Processname": "process3",
"CpuPercent": 0,
"MemoryPercent": 0.69,
}
]
}, {
"Timestamp": "11/18/2021 18:32:08",
"Processes": [{
"Timestamp": "11/18/2021 18:32:08",
"Processname": "process1",
"CpuPercent": 0,
"MemoryPercent": 0.16,
}, {
"Timestamp": "11/18/2021 18:32:09",
"Processname": "process2",
"CpuPercent": 0,
"MemoryPercent": 0.46,
}, {
"Timestamp": "11/18/2021 18:32:09",
"Processname": "process3",
"CpuPercent": 0,
"MemoryPercent": 0.69,
}
]
}, {...}
]}
I need to sum all the values based on process as key in another JSON like
{
"process1": {
"AverageCpu": xxx,
"AverageMemory": yyy,
},
"process2": {
"AverageCpu": xxx,
"AverageMemory": yyy,
},
"process3": {
"AverageCpu": xxx,
"AverageMemory": yyy,
}
}
I am trying with normal foreach with "groupby" but not able to get actual result.
I do not want to iterate many times as this source JSON can be huge.
Thanks
You can use tools such as Json2Csharp to generate the classes based on JSON.
public class Process
{
public string Timestamp { get; set; }
public string Processname { get; set; }
public int CpuPercent { get; set; }
public double MemoryPercent { get; set; }
}
public class Stat
{
public string Timestamp { get; set; }
public List<Process> Processes { get; set; }
}
public class Root
{
public string Nodename { get; set; }
public string OperatingSystem { get; set; }
public string Release { get; set; }
public List<Stat> Stats { get; set; }
}
public class GroupedProcessStat
{
public double AverageCpu {get;set;}
public double AverageMemory {get;set;}
}
Deserialize JSON to Root class via Newtonsoft.Json.JsonConvert.
Retrieve processes via .SelectMany() from System.Linq.
.GroupBy() processName and convert it to dictionary via .ToDictionary().
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
var root = JsonConvert.DeserializeObject<Root>(json);
var processes = root.Stats
.SelectMany(x => x.Processes)
.ToList();
var groupedProcessDict = processes.GroupBy(x => x.Processname)
.ToDictionary(
x => x.Key,
x => new GroupedProcessStat
{
AverageCpu = x.Average(y => y.CpuPercent),
AverageMemory = x.Average(y => y.MemoryPercent)
});
var groupedProcessJson = JsonConvert.SerializeObject(groupedProcessDict);
Console.WriteLine(groupedProcessJson);
Output
{"process1":{"AverageCpu":0.0,"AverageMemory":0.16},"process2":{"AverageCpu":0.0,"AverageMemory":0.46},"process3":{"AverageCpu":0.0,"AverageMemory":0.69}}
Sample Program on .NET Fiddle

How do i make this string a JSON object?

How can I turn the string fetched from the URL to a usable object? I've seen several Newtonsoft.Json examples, but none of them work with the layout of the object in the URL.
The code below is what I have so far. (the DeserializeObject part currently in the code doesn't work) due to the layout of the object.
JSON Data:
{
"totals": {
"confirmed": 4011,
"dead": 23,
"recovered": 7,
"changes": {
"newToday": 239,
"newYesterday": 378,
"diff": -139,
"deathsToday": 4,
"deathsYesterday": 5
}
},
"cases": [
{
"confirmed": 989,
"dead": 4,
"recovered": 1,
"name": "Oslo",
"countyCode": "03",
"confirmedPer1kCapita": 1.426111833700075
},
{
"confirmed": 1138,
"dead": 7,
"recovered": 1,
"name": "Viken",
"countyCode": "30",
"confirmedPer1kCapita": 0.9168805114549636
},
{
"confirmed": 284,
"dead": 2,
"recovered": 1,
"name": "Innlandet",
"countyCode": "34",
"confirmedPer1kCapita": 0.7647050904048359
},
{
"confirmed": 440,
"dead": 0,
"recovered": 3,
"name": "Vestland",
"countyCode": "46",
"confirmedPer1kCapita": 0.6912467735271338
},
{
"confirmed": 304,
"dead": 0,
"recovered": 0,
"name": "Rogaland",
"countyCode": "11",
"confirmedPer1kCapita": 0.633475865403049
},
{
"confirmed": 285,
"dead": 0,
"recovered": 0,
"name": "Trøndelag",
"countyCode": "50",
"confirmedPer1kCapita": 0.608062265575995
},
{
"confirmed": 130,
"dead": 2,
"recovered": 0,
"name": "Troms og Finnmark",
"countyCode": "54",
"confirmedPer1kCapita": 0.5342956134330138
},
{
"confirmed": 159,
"dead": 1,
"recovered": 0,
"name": "Agder",
"countyCode": "42",
"confirmedPer1kCapita": 0.5175259007066344
},
{
"confirmed": 149,
"dead": 1,
"recovered": 0,
"name": "Vestfold og Telemark",
"countyCode": "38",
"confirmedPer1kCapita": 0.3552728209138857
},
{
"confirmed": 91,
"dead": 0,
"recovered": 1,
"name": "Møre og Romsdal",
"countyCode": "15",
"confirmedPer1kCapita": 0.34308809446610217
},
{
"confirmed": 42,
"dead": 0,
"recovered": 0,
"name": "Nordland",
"countyCode": "18",
"confirmedPer1kCapita": 0.17410408937343255
}
],
"updated": {
"ts": "2020-03-28T21:23:18+01:00",
"by": "Morten Asbjørnsen",
"version": "5154"
}
}
Code:
public class Program
{
public static void Main(string[] args)
{
string Address = "https://redutv-api.vg.no/corona/v1/sheets/norway-table-overview?region=county";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Address);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (String.IsNullOrWhiteSpace(response.CharacterSet))
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
Console.WriteLine(data);
//No clue...
Statistic statistic = JsonConvert.DeserializeObject<Statistic>(data);
}
}
public class Statistic
{
//needs modifying.
public string confirmed.total {get;set;}
}
}
Your c# class has to have structure similar to json
(Note: I'm specifically skipping some details of deserialization for simplicity, but in short the parts of your C# class that don't match your json will be skipped - you will have default values)
Here's what you can do
Download your json from https://redutv-api.vg.no/corona/v1/sheets/norway-table-overview?region=county
Generate a c# class based on that json using some tool, for example http://json2csharp.com/ or https://www.jsonutils.com/
Rename the generated RootObject into something meaningful - this is your Statistics class
Depending on the tooling you will get a slightly different result, something similar to the code below
(Note: Some details may differ, like collection types can use array, List<T> or IList<T> depending on the tooling)
As a bonus, if you're able to use .NET Core 3x, Try the new System.Text.Json APIs - this is the recommended approach going forward, not Newtonsoft.JSON
public class Changes
{
public int newToday { get; set; }
public int newYesterday { get; set; }
public int diff { get; set; }
public int deathsToday { get; set; }
public int deathsYesterday { get; set; }
}
public class Totals
{
public int confirmed { get; set; }
public int dead { get; set; }
public int recovered { get; set; }
public Changes changes { get; set; }
}
public class Case
{
public int confirmed { get; set; }
public int dead { get; set; }
public int recovered { get; set; }
public string name { get; set; }
public string countyCode { get; set; }
public double confirmedPer1kCapita { get; set; }
}
public class Updated
{
public DateTime ts { get; set; }
public string by { get; set; }
public string version { get; set; }
}
public class RootObject
{
public Totals totals { get; set; }
public List<Case> cases { get; set; }
public Updated updated { get; set; }
}
You need an object structure in C# which matches the structure of the JSON you're downloading.
Sites like json2csharp will auto-generate a structure for you and will work with most JSON you can think of.
For the data presented by that URL when I visited it just now, it suggests this:
public class Changes
{
public int newToday { get; set; }
public int newYesterday { get; set; }
public int diff { get; set; }
public int deathsToday { get; set; }
public int deathsYesterday { get; set; }
}
public class Totals
{
public int confirmed { get; set; }
public int dead { get; set; }
public int recovered { get; set; }
public Changes changes { get; set; }
}
public class Case
{
public int confirmed { get; set; }
public int dead { get; set; }
public int recovered { get; set; }
public string name { get; set; }
public string countyCode { get; set; }
public double confirmedPer1kCapita { get; set; }
}
public class Updated
{
public DateTime ts { get; set; }
public string by { get; set; }
public string version { get; set; }
}
public class RootObject
{
public Totals totals { get; set; }
public List<Case> cases { get; set; }
public Updated updated { get; set; }
}
You can then run
RootObject obj = JsonConvert.DeserializeObject<RootObject>(data);
to deserialise it.
/* method arguments:
stream : Stream class instance
charSet: Character set (in string), default is current system encoding.
bufferSize: Buffer size, default 1024 bytes
*/
static async Task<string> readStreamAsync(Stream stream, string charSet = "", int bufferSize = 1024)
{
/* read stream to buffers */
var buffer = new byte[bufferSize];
List<byte> buffers = new List<byte>();
using (var readStream = new StreamReader(stream))
{
// read stream into buffer
var n = await readStream.ReadAsync(buffer, 0, bufferSize);
// loop buffer streaming until no more stream data
while (n > 0)
{
// populate buffer into buffer list
buffers.AddRange(new ArraySegment<byte>(buffer, 0, n).Array);
// read stream into buffer
n = await readStream.ReadAsync(buffer, 0, bufferSize);
}
}
/* return encoded string */
if (String.IsNullOrWhiteSpace(charSet))
{
// encode buffers array into default encoded string
return Encoding.Default.GetString(buffers.ToArray());
}
else
{
// encode buffers array into encoded string based on any character set
return Encoding.GetEncoding(charSet).GetString(buffers.ToArray());
}
}
/* usage: */
string data;
try
{
using (var receiveStream = response.GetResponseStream())
{
data = await readStreamAsync(receiveStream, response.CharacterSet);
}
}
finally
{
response.Close();
}
Console.WriteLine(data);
Statistic statistic = JsonConvert.DeserializeObject<Statistic>(data);

Getting strange error in Unity while creating an inventory system

So I wanted to create an inventory system and I have coded and done a few things. However now it is showing an error in the item database code. The error is:
KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary2[System.Int32,System.Collections.Generic.IDictionary2[System.Int32,System.Int32[]]].get_Item (Int32 key) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
LitJson.JsonReader.Read ()
Rethrow as JsonException: Invalid token '123' in input string
LitJson.JsonReader.Read ()
LitJson.JsonMapper.ReadValue (LitJson.WrapperFactory factory, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (LitJson.WrapperFactory factory, LitJson.JsonReader reader)
LitJson.JsonMapper.ReadValue (LitJson.WrapperFactory factory, LitJson.JsonReader reader)
LitJson.JsonMapper.ToWrapper (LitJson.WrapperFactory factory, System.String json)
LitJson.JsonMapper.ToObject (System.String json)
ItemDatabase.Start () (at Assets/All/Scripts/ItemDatabase.cs:13)
and it became very annoying since I couldn't figure out how to fix it. My 2 files currently are:
using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
using System.IO;
public class ItemDatabase : MonoBehaviour {
private List<Item> database = new List<Item>();
private JsonData itemData;
void Start()
{
itemData = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/StreamingAssets/Items.json"));
ConstructItemDatabase();
Debug.Log(database[1].Slug);
}
void ConstructItemDatabase()
{
for (int i = 0; i < itemData.Count; i++)
{
database.Add(new Item((int)itemData[i]["id"], itemData[i]["title"].ToString(), (int)itemData[i]["value"],
(int)itemData[i]["stats"]["power"], (int)itemData[i]["stats"]["defence"], (int)itemData[i]["stats"]["vitality"], itemData[i]["description"].ToString(),
(bool)itemData[i]["stackable"], (int)itemData[i]["rarity"],
itemData[i]["slug"].ToString()));
}
}
}
public class Item
{
public int ID { get; set; }
public string Title { get; set; }
public int Value { get; set; }
public int Power { get; set; }
public int Defence { get; set; }
public int Vitality { get; set; }
public string Description { get; set; }
public bool Stackable { get; set; }
public int Rarity { get; set; }
public string Slug { get; set; }
public Item(int id, string title, int value, int power, int defence, int vitality, string description, bool stackable, int rarity, string slug)
{
this.ID = id;
this.Title = title;
this.Value = value;
this.Power = power;
this.Defence = defence;
this.Vitality = vitality;
this.Description = description;
this.Stackable = stackable;
this.Rarity = rarity;
this.Slug = slug;
}
public Item()
{
this.ID = -1;
}
}
Here the top one is my ItemDatabase.cs file. It has a few spaces and brackets are wrong I know but it is actually all fine. I will post a screenshot with the whole code. Since I am new to using this Code Sample tool.
And here is my Items.json file.
[
{
"id": 0,
"title": "Wood Pickaxe",
"value": 6,
"stats" {
"power": 1,
"defence": 0,
"vitality": 0
},
"description": "A basic wood pickaxe.",
"stackable": false,
"rarity": 1,
"slug": "wood_pickaxe"
},
{
"id": 1,
"title": "Wood Pickaxe Head",
"value": 543,
"stats" {
"power": 1,
"defence": 0,
"vitality": 0
},
"description": "A piece of a broken wood pickaxe.",
"stackable": false,
"rarity": 1,
"slug": "wood_pickaxe_head"
}
]
I will also post a screenshot of this code. Please help. This is very frustrating and the other posts about this won't help. Items.json screenshot ItemDatabase.cs screenshot
You have an error in your json. The error itself is a little misleading. Every time I've seen it, there was a json syntax issue involved.
[
{
"id": 0,
"title": "Wood Pickaxe",
"value": 6,
"stats": { // <-- problem was here. missing colon
"power": 1,
"defence": 0,
"vitality": 0
},
"description": "A basic wood pickaxe.",
"stackable": false,
"rarity": 1,
"slug": "wood_pickaxe"
},
{
"id": 1,
"title": "Wood Pickaxe Head",
"value": 543,
"stats": { // <-- problem was here. missing colon
"power": 1,
"defence": 0,
"vitality": 0
},
"description": "A piece of a broken wood pickaxe.",
"stackable": false,
"rarity": 1,
"slug": "wood_pickaxe_head"
}
]

How to serialize a javascript array object in Newtonsoft JsonConvert in C#

I want to serialize javascript array to object using Newtonsoft JsonConvert in C#. Any help would be appreciated.
My Javascript array object is:
[
{
"ID": 0,
"Patient_ID": 1,
"Appointment_ID": 219,
"ObservationID": "33",
"arrOption": "{\"ObservationOptionList\":[{\"Observations_Param_Option_ID\":\"77\",\"Extended_Value\":\"\"}]}"
},
{
"ID": 0,
"Patient_ID": 1,
"Appointment_ID": 219,
"ObservationID": "1",
"arrOption": "{\"ObservationOptionList\":[{\"Observations_Param_Option_ID\":\"1\",\"Extended_Value\":\"Dry\"}]}"
},
{
"ID": 0,
"Patient_ID": 1,
"Appointment_ID": 219,
"ObservationID": "8",
"arrOption": "{\"ObservationOptionList\":[{\"Observations_Param_Option_ID\":\"25\",\"Extended_Value\":\"\"}]}"
},
{
"ID": 0,
"Patient_ID": 1,
"Appointment_ID": 219,
"ObservationID": "15",
"arrOption": "{\"ObservationOptionList\":[{\"Observations_Param_Option_ID\":\"40\",\"Extended_Value\":\"\"}]}"
}
]
I assume you mean de-serialize.
Create a class to hold each Patient.
public class Patient
{
public int ID { get; set; }
public int Patient_ID { get; set; }
public int Appointment_ID { get; set; }
public string ObservationID { get; set; }
public string arrOption { get; set; }
}
Deserialize into a List of Patient.
var patients = JsonConvert.DeserializeObject<List<Patient>>(json);
Create a C# Class
class MyClass
{
public int ID {get;set;}
public int Patient_ID {get;set;}
public int Appointment_ID {get;set;}
public string ObservationID {get;set;}
public string arrOption {get;set;
}
Now use deserialize method
new JavaScriptSerializer().Deserialize<MyClass>(jsonString);
If you also want deserialize arrOption to a object you need to foreach after deserialize

Categories

Resources