how to convert json array to Dataset using C# - 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.

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;

Convert Json string into C# DataTable

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.

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);
}

How to recognize DateTime fields as such when assigning a Json.net JArray to a Grid?

My winform client requests a DataTable from server to assign to Grid on forms.
The server will return DataTable as JSON using JSON.net.
We use JArray.Parse to read the returned string and assign this JArray to Grid.
The data is displayed well except for DateTime fields.
All of fields with DateTime type have names that contain "DATE" or "TIME".
I wonder if there is any way to parse JTokens that belong to these fields to DateTime format?
I am using C# with VS2013 .Net 4.0
My returned json string is:
[
{ "ORDER_ID":10, "CREATED_DATE":"20160617181008", "NOTE":"Hello" },
{ "ORDER_ID":20, "CREATED_DATE":"20160616140302", "NOTE":"Ciao" }
]
I parse this JSON string as follows:
JArray table = JArray.Parse(jsonString);
And I assign the variable "table" to DataSource of Grid Control.
I am using the following C# date format: "yyyyMMddHHmmss".
The grid will display CREATED_DATE column as: 20160617181008 and 20160616140302.
It would be easiest if you could output dates and times from the server to JSON in ISO 8601 format. If a date string is formatted in this style, LINQ to JSON will automatically recognize it as a DateTime and deserialize it as such. See Deserializing from JSON with LINQ and Serializing Dates in JSON for details.
That being said, you can post-process your JArray to convert the value of any property with "DATE" or "TIME" in its name to a DateTime as follows:
var table = JArray.Parse(jsonString);
var format = "yyyyMMddHHmmss";
var culture = CultureInfo.InvariantCulture; // Change if necessary
var style = DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal; // Change if necessary.
foreach (var property in table.Descendants().OfType<JProperty>().Where(p => (p.Name.Contains("DATE") || p.Name.Contains("TIME")) && p.Value.Type == JTokenType.String))
{
var value = (string)property.Value;
DateTime date;
if (DateTime.TryParseExact(value, format, culture, style, out date))
property.Value = date;
}

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;
}

Categories

Resources