How to deserialize the above JSON string to datatable in c# - c#

How can I deserialize the following JSON string to a datatable in c#
{
"m_MaxCapacity":2147483647,
"Capacity":1888,
"m_StringValue":"<table border=3><tr><th>Master ID</th><th>Tag ID</th><th>Plant ID</th><th>Machine Name</th><th>Sap ID</th><th>Log</th></tr><tr><td>2296</td><td>567</td><td>567</td><td>hjhnh</td><td>567</td><td>17-09-2016 15:03:04</td></tr><tr><td>2297</td><td>55555</td><td>567</td><td>hjhnh</td><td>567</td><td>17-09-2016 15:04:27</td></tr><tr><td>2298</td><td>55555</td><td>567</td><td>hjhnh</td><td>0000</td><td>17-09-2016 15:04:53</td></tr><tr><td>2299</td><td>55555</td><td>567</td><td>hjhnh</td><td>0000</td><td>17-09-2016 15:05:11</td></tr><tr><td>2300</td><td>6678</td><td>6754</td><td>nnn</td><td>789</td><td>17-09-2016 15:20:51</td></tr><tr><td>2301</td><td>6678</td><td>6754</td><td>AF</td><td>789</td><td>17-09-2016 15:23:57</td></tr><tr><td>2302</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:33:22</td></tr><tr><td>2303</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:43:10</td></tr><tr><td>2304</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:43:23</td></tr><tr><td>2305</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>17-09-2016 15:43:50</td></tr><tr><td>2306</td><td>6678</td><td>6754</td><td>lmno</td><td>789</td><td>17-09-2016 15:49:25</td></tr><tr><td>2307</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 11:23:16</td></tr><tr><td>2308</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 11:40:07</td></tr><tr><td>2309</td><td>6678</td><td>6754</td><td>ccccc</td><td>789</td><td>22-09-2016 11:40:18</td></tr><tr><td>2310</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 11:45:53</td></tr><tr><td>2311</td><td>6678</td><td>6754</td><td>ttttttt</td><td>789</td><td>22-09-2016 12:00:48</td></tr><tr><td>2312</td><td>6678</td><td>6754</td><td>mmmmmmmmmm</td><td>789</td><td>22-09-2016 12:00:52</td></tr></table>",
"m_currentThread":0
}
Any ideas welcome.

First you have to add package Newtonsoft.Json to your project.Next create class with object. You can use http://json2csharp.com/ it's very helpfull tool. Finally you have to Deserialize yours json. Try use this sample.
public class RootObject
{
public long m_MaxCapacity { get; set; }
public int Capacity { get; set; }
public string m_StringValue { get; set; }
public int m_currentThread { get; set; }
}
string json= {"m_MaxCapacity":2147483647,"Capacity":1888,"m_StringValue":"Master IDTag IDPlant IDMachine NameSap IDLog2296567567hjhnh56717-09-2016 15:03:04229755555567hjhnh56717-09-2016 15:04:27229855555567hjhnh000017-09-2016 15:04:53229955555567hjhnh000017-09-2016 15:05:11230066786754nnn78917-09-2016 15:20:51230166786754AF78917-09-2016 15:23:57230266786754ttttttt78917-09-2016 15:33:22230366786754ttttttt78917-09-2016 15:43:10230466786754ttttttt78917-09-2016 15:43:23230566786754ttttttt78917-09-2016 15:43:50230666786754lmno78917-09-2016 15:49:25230766786754ttttttt78922-09-2016 11:23:16230866786754ttttttt78922-09-2016 11:40:07230966786754ccccc78922-09-2016 11:40:18231066786754ttttttt78922-09-2016 11:45:53231166786754ttttttt78922-09-2016 12:00:48231266786754mmmmmmmmmm78922-09-2016 12:00:52","m_currentThread":0}
List<RootObject> list = new List<RootObject>();
list= JsonConvert.DeserializeObject<List<RootObject>>(json);

you can use: http://json2csharp.com/
there you get the class:
public class RootObject
{
public long m_MaxCapacity { get; set; }
public int Capacity { get; set; }
public string m_StringValue { get; set; }
public int m_currentThread { get; set; }
}
then you can add it to your context.

Related

Json class saving a value while containing other default values

Hey all I am trying to figure out how to go about saving just one value in my JSON class instead of having to write the whole JSON out again with "New". I am using the Newton JSON.Net.
This is my JSON structure:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
And I have no issues with loading that data from a file into my class:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(#"\Resources\{0}", "dataForLinks.json")
));
But I have yet to find anything searching that will let me do one update to an object in the class without wiping it out doing a New statement.
What I am wanting to do is something like the following:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
When I update just that one class object I am wanting to contain the original values for all the other JSON data I read in from the file.
Anyone have a good example of the above you can share?
update
I'd ditch the inner class structure:
namespace GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public double LastSavedVolume { get; set; }
}
public class Root
{
public Data Data { get; set; }
}
Deser (use Path.Combine to build paths, not string concat):
var x = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
Path.Combine(currentAssemblyPath, "Resources", "dataForLinks.json"))
));
Edit:
x.Data.PathToNESContent = "...";
and re-ser

Why does deserialized JSON array return null?

I have a string stream returning JSON data from and API that looks like this:
"{\"Recs\":
[
{\"EID\":\"F67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"NA\"},
{\"EID\":\"T67_24_6\",\"ReturnPeriod\":\"2.37\",\"GageStation\":\"Magueyes Island\"},
{\"EID\":\"R67_24_6\",\"ReturnPeriod\":\"1\",\"GageStation\":\"50147800\"}
]}"
I am trying to deserialize it to return this:
{"Recs":[
{"EID":"F67_24_6","ReturnPeriod":"1","GageStation":"NA"},
{"EID":"T67_24_6","ReturnPeriod":"2.37","GageStation":"Magueyes Island"},
{"EID":"R67_24_6","ReturnPeriod":"1","GageStation":"50147800"}
]}
I am using these public classes to structure the return:
public class New_Events_Dataset
{
public string EID { get; set; }
public string ReturnPeriod { get; set; }
public string GageStation { get; set; }
}
public class NewRootObject
{
public List<New_Events_Dataset> Reqs { get; set; }
}
When I try to apply this later, I basically get a return of {"Reqs":null}. What am I doing wrong here?
var jsonResponse = JsonConvert.DeserializeObject<NewRootObject>(strresult);
string json = new JavaScriptSerializer().Serialize(jsonResponse);
return json;
I think Reqs should be Recs:
public class NewRootObject
{
public List<New_Events_Dataset> Reqs { get; set; }
}
try:
public class NewRootObject
{
public List<New_Events_Dataset> Recs { get; set; }
}
Rename Reqs to Recs and create default constructor of class and instantiate Recs list
public class NewRootObject
{
List<New_Events_Dataset> Recs { get; set; }
public NewRootObject()
{
Recs = new List<New_Events_Dataset>();
}
}

Getting NULL values while deserializing complex json

My project has a 3rd party web API that returns a json string in the following format (including the starting and ending curly braces):
{
"866968030210604":{
"dt_server":"2019-02-07 12:21:27",
"dt_tracker":"2019-02-07 12:21:27",
"lat":"28.844968",
"lng":"76.858502",
"altitude":"0",
"angle":"154",
"speed":"9",
"params":{
"pump":"0",
"track":"1",
"bats":"1",
"acc":"0",
"batl":"4"
},
"loc_valid":"1"
},
"866968030221205":{
"dt_server":"2019-02-07 12:20:24",
"dt_tracker":"2019-02-07 12:19:41",
"lat":"28.845904",
"lng":"77.096063",
"altitude":"0",
"angle":"0",
"speed":"0",
"params":{
"pump":"0",
"track":"1",
"bats":"1",
"acc":"0",
"batl":"4"
},
"loc_valid":"1"
},
"866968030212030":{
"dt_server":"0000-00-00 00:00:00",
"dt_tracker":"0000-00-00 00:00:00",
"lat":"0",
"lng":"0",
"altitude":"0",
"angle":"0",
"speed":"0",
"params":null,
"loc_valid":"0"
}
}
I want to deserialize it into a c# class object for further processing. I made the following class structure for the same:
class Params
{
public string pump { get; set; }
public string track { get; set; }
public string bats { get; set; }
public string acc { get; set; }
public string batl { get; set; }
}
class GPSData
{
public string dt_server { get; set; }
public string dt_tracker { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string altitude { get; set; }
public string angle { get; set; }
public string speed { get; set; }
public Params ObjParams { get; set; }
public string loc_valid { get; set; }
}
and I am trying the following code to deserialize:
JavaScriptSerializer jSerObj = new JavaScriptSerializer();
List<GPSData> lstGPSData = (List<GPSData>)jSerObj.Deserialize(json, typeof(List<GPSData>));
But every time it is showing NULL values assigned to each property of the class after the Deserialize() method is called. Please help me on this.
Your json is not in list format so deserializing to List<> isn't work
So you need to deserialize it into Dictionary<string, GPSData> like
JavaScriptSerializer jSerObj = new JavaScriptSerializer();
Dictionary<string, GPSData> lstGPSData = (Dictionary<string, GPSData>)jSerObj.Deserialize(json, typeof(Dictionary<string, GPSData>));
Usage:
foreach (var item in lstGPSData)
{
string key = item.Key;
GPSData gPSData = item.Value;
}
Also, you can list all your GPSData from above dictionary like,
List<GPSData> gPSDatas = lstGPSData.Values.ToList();
Output: (From Debugger)

Deserialize JSON objects one by one using json.net (XAMARIN)

I'm new to this. I'm using Xamarin in VS2017.
I have a JSON file as follows
[ {
"LEDGERID":1,
"LEDGERNAME":"CASH",
"UNDER":"19",
"CREDIT_PERIOD":"0",
"CREDIT_LIMIT":"0",
"LEDGER_TYPE":"DEBIT",
"OPENBAL":120196.00,
"STATUS":"True",
"USER_GEN":false,
"date":null,
"arabic_name":null},
{
"LEDGERID":2,
"LEDGERNAME":"PURCHASE",
"UNDER":"17",
"CREDIT_PERIOD":"0",
"CREDIT_LIMIT":"0",
"LEDGER_TYPE":"DEBIT",
"OPENBAL":0.00,
"STATUS":"True",
"USER_GEN":false,
"date":null,
"arabic_name":null
}
]
This is a lengthier one but i made it short for easy understanding. I need to take it one by one because sometimes I need to give test cases before taking the values to the list. I am using PCL storage in XAMARIN tostore the Json File. I went througn the documents of NewtonSoft Json deserializing. I hope some one can help me thanks in advance
Your json isn't valid, you had the word nul, however i'm sure it was a mistake
Take your json to http://json2csharp.com/ and create a class from it and call it what ever you want
Get your self the Json.net Nuget package
Example class
public class RootObject
{
public int LEDGERID { get; set; }
public string LEDGERNAME { get; set; }
public string UNDER { get; set; }
public string CREDIT_PERIOD { get; set; }
public string CREDIT_LIMIT { get; set; }
public string LEDGER_TYPE { get; set; }
public double OPENBAL { get; set; }
public string STATUS { get; set; }
public bool USER_GEN { get; set; }
public object date { get; set; }
public object arabic_name { get; set; }
}
Usage
var results = JsonConvert.DeserializeObject<List<RootObject>>(json);

Deserialise JSON containing numeric key with Json.NET

I would like to deserialize the following JSON (using Json.NET) to an object, but cannot, as the class name would need to begin with a number.
An example of this is the Wikipedia article API. Using the API to provide a JSON response returns something like this. Note the "16689396" inside the "pages" key.
{
"batchcomplete":"",
"continue":{
"grncontinue":"0.893378504602|0.893378998188|35714269|0",
"continue":"grncontinue||"
},
"query":{
"pages":{
"16689396":{
"pageid":16689396,
"ns":0,
"title":"Jalan Juru",
"extract":"<p><b>Jalan Juru</b> (Penang state road <i>P176</i>) is a major road in Penang, Malaysia.</p>\n\n<h2><span id=\"List_of_junctions\">List of junctions</span></h2>\n<p></p>\n<p><br></p>"
}
}
}
}
How could I deserialize this JSON containing a number which changes based on the article?
It sounds like the Pages property in your Query class would just need to be a Dictionary<int, Page> or Dictionary<string, Page>.
Complete example with the JSON you've provided - I've had to guess at some of the name meanings:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
public class Root
{
[JsonProperty("batchcomplete")]
public string BatchComplete { get; set; }
[JsonProperty("continue")]
public Continuation Continuation { get; set; }
[JsonProperty("query")]
public Query Query { get; set; }
}
public class Continuation
{
[JsonProperty("grncontinue")]
public string GrnContinue { get; set; }
[JsonProperty("continue")]
public string Continue { get; set; }
}
public class Query
{
[JsonProperty("pages")]
public Dictionary<int, Page> Pages { get; set; }
}
public class Page
{
[JsonProperty("pageid")]
public int Id { get; set; }
[JsonProperty("ns")]
public int Ns { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("extract")]
public string Extract { get; set; }
}
class Test
{
static void Main()
{
string text = File.ReadAllText("test.json");
var root = JsonConvert.DeserializeObject<Root>(text);
Console.WriteLine(root.Query.Pages[16689396].Title);
}
}
Related question: Json deserialize from wikipedia api with c#
Essentially you need to changes from using a class for the pages to a dictionary, which allows for the dynamic nature of the naming convention.
Class definitions :
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
Deserialization :
var root = JsonConvert.DeserializeObject<RootObject>(__YOUR_JSON_HERE__);
var page = responseJson.query.pages["16689396"];
You can implement your own DeSerializer or editing the JSON before you DeSerialize it.

Categories