Convert Json string into C# DataTable - c#

I am absolutely new in Json stuff, following is one of my returned JSON string from one of the Internal REST API Call:
{
"odata.metadata":"https://ABC.XYZ.com/ERP10TESTNSSO/api/v1/Erp.BO.ABCCodeSvc/$metadata#Epicor.RestApi.ABCCodes/#Element",
"Company":"93100",
"ABCCode1":"A",
"CountFreq":1,
"ExcludeFromCC":false,
"StockValPcnt":"0",
"PcntTolerance":"0.00",
"CalcPcnt":false,
"CalcQty":false,
"CalcValue":false,
"QtyTolerance":"0",
"ValueTolerance":"0",
"ShipToCustNum":0,
"SysRevID":"6066188743",
"SysRowID":"5b7e2172-7f7a-445e-983d-f230e050153d",
"BitFlag":0,
"RowMod":""
}
Please let me know, how may I convert it into C# Data Table?
I tried following code (posted by another kind techie)
dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonContent);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(Convert.ToString(jsonObject.Value));
But this code is throwing error at jsonObject.Value.
Please help me to fix it ...

Try this:
string json = "{\"odata.metadata\":\"https://ABC.XYZ.com/ERP10TESTNSSO/api/v1/Erp.BO.ABCCodeSvc/$metadata#Epicor.RestApi.ABCCodes/#Element\",\"Company\":\"93100\",\"ABCCode1\":\"A\",\"CountFreq\":1,\"ExcludeFromCC\":false,\"StockValPcnt\":\"0\",\"PcntTolerance\":\"0.00\",\"CalcPcnt\":false,\"CalcQty\":false,\"CalcValue\":false,\"QtyTolerance\":\"0\",\"ValueTolerance\":\"0\",\"ShipToCustNum\":0,\"SysRevID\":\"6066188743\",\"SysRowID\":\"5b7e2172-7f7a-445e-983d-f230e050153d\",\"BitFlag\":0,\"RowMod\":\"\"}";
json = $"[{json}]";
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
Add [ ] in your json string.

Related

How to get data from a nested json in c#

{"data": {"day2": {"mId": "9ilrMdX15S", "votes": "2,893"},"day3": {"mId": "9ilert415S","votes": "2,343"}}}
How can i retrieve the data from a json data as such (i.e the data in "day2", or "day3") i followed the answers here > Appending json data to listview c# by Brain Rogers but the answer only work for json object not for nested json.
Here's an example of how to navigate it:
foreach (JProperty day in JObject.Parse(json)["data"])
{
string name = day.Name;
string id = day.Value.Value<string>("mId");
string votes = day.Value.Value<string>("votes");
}
Thanks for all the response, i was able to solve the task using the SimpleJSON library by Bunny83 GitHub - Bunny83/SimpleJSON: A simple JSON parser in C#
JSONNode data = JSON.Parse(//jsonData or Url//);
string mId = data["data"]["day2"]["mId"].Value;
string votes = data["data"]["day2"]["votes"].Value;

How to parse JSON with Newtonsoft?

I created an ASP.NET Application, where I have to parse a csv file with a json structure.
The csv file itself is structured like:
{"Instance":"abc","Date":"2019-06-03T00:00:02.056Z","Identification":"someFunction","Type":"DurationInMs","Value":"5","iserror":"False""}
I get the jsonCsvData as a string and tried to parse it. Then I want to save some of the elements of this json object into a db.
public IActionResult ReadJsonCsvData(string jsonCsvData)
{
Console.WriteLine("ReadJsonCsvData");
ChartData chartData = new ChartData();
var lines = jsonCsvData.Split("\n");
foreach (var line in lines)
{
var values = JObject.Parse(line);
var first = string.Concat(values["Instance"]); //Output for first: ""
}
}
The problem now is, that the variable first is an empty string. The result should be (like in the json structure example above) "abc".
Thank you in advance!
I don't know if it will help but here is my solution (remove one of " at the end of your Json).
I use the "Jobject" to parse Json as I want. Import this two reference.
using Newtonsoft.Json.Linq;
using Newtonsoft;
Then you have to create your JObject :
JObject o = JObject.Parse(myJsonString);
Then to retrieve specifics data, you just have to search in your object just like you do with a dictionary with key :
instanceFromJson = o["Instance"].ToString;
dateFromJson = o["Date"].ToString;
If you have a table in your "instance" json object you can retrieve all data from this list just like that :
foreach (var item in o["Instance"]["tabFromInstanceObject"])
{
MyList.Add(item);
}

Unable to parse JSON file format

I have the following JSON in a text file which I am trying to parse.
{
"0":[68],
"1":[154,78,61],
"2":[89,132,146],
"3":[],
"4":[77,132,146],
"5":[32,132,50],
"6":[],
"7":[114,118,54,44,72,136,156,134,129,82,43,34,51,93,142,67,47,153,160,73,39,149,107,94,145,29,115,53,83,1,35,56,123,66,90,121,155],
"8":[89,146],
"9":[89,146],
"10":[100,135],
"11":[],
"12":[],
"13",[111,131],
"14":[77,124],
"15":[89,146],
"16":[163,126,122],
"17":[100,126,135],
"18":[32,50],
"19":[163,126,122]
}
The code I have is
var map = new List<Dictionary<int, List<int>>>();
using (var r = new StreamReader(#"C:\Development\phase2\dependencymap.json"))
{
var json = r.ReadToEnd();
map = JsonConvert.DeserializeObject<List<Dictionary<int, List<int>>>>(json);
}
But it doesn't seem to like the format. What am I doing wrong?
The JSON is malformed. Check the following line
"13" , [111,131],
and change it to:
"13" : [111,131],
Try map = JsonConvert.DeserializeObject<List<Dictionary<String, List<int>>>>(json);
Your keys are String, not int.

Convert to JSON Array, not regular object

I have used this utility http://www.convertcsv.com/csv-to-json.htm to format tables of data. It has the wonderful option of allowing you to convert to JSON or to a JSON Array. That JSON Array is what I want. When I use utilities like JSON.Net to serialize, they give me the standard JSON format. I don't want that - I just want arrays, so I can basically reproduce a table layout in my javascript.
Here is sample table data structure
column1 column2 column3
c1r1 c2r1 c3r1
c1r2 c2r2 c3r2
c1r3 c2r3 c3r3
I want it to look like this when serialized:
[[c1r1,c2r1,c3r1],
[c1r2,c2r2,c3r2],
[c1r3,c2r3,c3r3]]
But the standard serialization method with a utility like JSON.net would be
[
{
column1:c1r1,
column2:c2r1,
column3:c3r1
},
{
column1:c1r2,
column2:c2r2,
column3:c3r2
},
{
column1:c1r3,
column2:c2r3,
column3:c3r3
}
]
My question is, does anyone know of a way of stripping out column names and just making it like the simple 2d array I have shown?
Data structure is an IEnumerable taken directly from a sql command db.Query("SELECT * FROM my_table").
Note: I want to have a generic function that can do this - I know how to do this for just one thing, but the project I'm working on needs it done for many in the same way. I tried to write my own method to do it, but it didn't work because of limitations that c# has.
public static string fromListToJSONArray(IEnumerable<Object> listToUse, string[] fieldNames)
{
string JSONString = "[";
foreach (var item in listToUse)
{
JSONString += item[fieldName[0]]; //This is the line you can't do in c#!! Don't know how to go around this.
}
JSONString += "]";
return JSONString;
}
What you are trying to output is an array of arrays. Starting with an enumerable or records (in your case it looks like it has columns called column1, column2, column3).
If the query will produce a know result set you can simple convert each row to an array before converting to JSON.
var qry = /*Enumerable of some database query*/
return from rec in wry
select new string[]
{
rec.column1,
rec.column2,
rec.column3
};
I think you're asking something similar to this.
You'll have to assemble the array manually from the json.
I found the solution - IEnumerable type needed to be "dynamic". From there it is pretty simple
public static string fromListToJSONArray(IEnumerable<dynamic> listToUse)
{
string JSONString = "[";
foreach (var item in listToUse)
{
if(isFirst == false)
JSONString += ",";
else
isFirst = false;
JSONString += "\"" + item[0] + "\"";
}
JSONString += "]";
return JSONString;
JSONString += "]";
return JSONString;
}

how to convert json array to Dataset using C#

I have a Json String like this,
var JSARR=
"[[{"BRANDID":"172","VARNAME":"sd",
"ETLVARID":"1","ETLVARNAME":"Ariel_Ariel_Print",
"ISFOR":0,"ISDEP":"1"},
{"BRANDID":"172","VARNAME":"h",
"ETLVARID":"1","ETLVARNAME":"Ariel_Ariel_TV",
"ISFOR":0,"ISDEP":"0"}],
[{"BRANDID":"238","VARNAME":"df",
"ETLVARID":"1","ETLVARNAME":"Ariel_Ariel_TV",
"ISFOR":0,"ISDEP":"1"},{"BRANDID":"238","VARNAME":"dfh",
"ETLVARID":"2","ETLVARNAME":"Ariel_Ariel Detergent_Print",
"ISFOR":0,"ISDEP":"0"}]]";
i need to convert this json String to two datatable,
for example:
Datatable dt1="[{"BRANDID":"172","VARNAME":"sd",
"ETLVARID":"1","ETLVARNAME":"Ariel_Ariel_Print",
"ISFOR":0,"ISDEP":"1"},
{"BRANDID":"172","VARNAME":"h",
"ETLVARID":"1","ETLVARNAME":"Ariel_Ariel_TV",
"ISFOR":0,"ISDEP":"0"}]";
Datatable dt2="[{"BRANDID":"238","VARNAME":"df",
"ETLVARID":"1","ETLVARNAME":"Ariel_Ariel_TV",
"ISFOR":0,"ISDEP":"1"},{"BRANDID":"238","VARNAME":"dfh",
"ETLVARID":"2","ETLVARNAME":"Ariel_Ariel Detergent_Print",
"ISFOR":0,"ISDEP":"0"}]";
Can Any one suggest me.

Categories

Resources