I have incoming JSON formatted like this:
{
"users": [
{
"radio_id": "123582",
"callsign": "ABCD",
"name": "First Last",
"city": "Dortmund",
"state": "Nordrhein-Westfalen",
"country": "Germany",
"home_rptr": "W2VL",
"remarks": "None"
},
{
"radio_id": "789456",
"callsign": "EFG",
"name": "Name Here",
"city": "Dortmund",
"state": "Nordrhein-Westfalen",
"country": "Germany",
"home_rptr": "W2VL",
"remarks": "None"
}
]
}
It is coming from a web request that I catch into a string called dataReceived. I then use this line of code to convert to a datatable.
DataTable dtData = (DataTable)JsonConvert.DeserializeObject(dataReceived, (typeof(DataTable)));
I'm getting an error of:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
I suspect my problem is the data is in an array, but I'm not sure how to solve this. My objective is to have a table with each row one of the "users" objects in the json.
Can anyone push me in the right direction?
var dt = JObject.Parse(json)["users"].ToObject<DataTable>();
That is all.
Related
Hi every one it is possible to convert json to debatable without doing loop
{
"ipAddress": "10.203.10.162",
"portNo": 45462,
"protocol": "HTTP",
"macAddress": "98:df:82:86:a4:27",
"channelID": 1,
"dateTime": "2023-01-11T14:57:24+04:00",
"activePostCount": 1,
"eventType": "AccessControllerEvent",
"eventState": "active",
"eventDescription": "Access Controller Event",
"AccessControllerEvent": {
"deviceName": "Access Controller",
"majorEventType": 5,
"subEventType": 75,
"name": "ahmad",
"cardReaderKind": 1,
"cardReaderNo": 1,
"verifyNo": 159,
"employeeNoString": "1",
"serialNo": 868,
"userType": "normal",
"currentVerifyMode": "cardOrFaceOrFp",
"currentEvent": false,
"frontSerialNo": 867,
"attendanceStatus": "breakOut",
"label": "Break Out",
"statusValue": 0,
"mask": "unknown",
"helmet": "unknown",
"picturesNumber": 1,
"purePwdVerifyEnable": true
}
}
I tried the following code and it return error.
DataTable dt = JsonConvert.DeserializeObject(json);
You have to flatten your JObject and only after this you can deserialize it to DataTable
var jo=JObject.Parse(json);
jo.Merge(jo["AccessControllerEvent"]);
jo.Remove("AccessControllerEvent");
DataTable dt = new JArray(jo).ToObject<DataTable>();
I suggest looking at uses of map: map documentation.
Under the hood, this of course is doing a for loop of a kind.
Perhaps you are trying to avoid the 'traditional' for loop, for this i use :
Object.Keys(yourJsonObect).foreach((key) => {
const someDataFromkey = yourJsonObect[key];
});
I hope that helps.
How to introduce the "attributes" level into JSON text below? I'm using a C# dataset populated from SQL server with SerializeObject from Newtonsoft.json.
This is for submitting data to ESRI batch geocoder, as described here.
The format their REST service expects looks like this
{
"records": [
{
"attributes": {
"OBJECTID": 1,
"Address": "4550 Cobb Parkway North NW",
"City": "Acworth",
"Region": "GA"
}
},
{
"attributes": {
"OBJECTID": 2,
"Address": "2450 Old Milton Parkway",
"City": "Alpharetta",
"Region": "GA"
}
}
]
}
The format my C# script creates looks like this (missing the "attributes" level.)
{
"records": [
{
"OBJECTID": 1,
"address": "4550 Cobb Parkway North NW",
"city": "Acworth",
"state": "GA",
"zip": 30101.0
},
{
"OBJECTID": 2,
"address": "2450 Old Milton Parkway",
"city": "Alpharetta",
"state": "GA",
"zip": 30009.0
}
]
}
I've read thru json.net documentation and wonder if the JsonConverter class could be helpful. Candidly, I'm at loss for how to resolve this. First time user of Json.net, relative newbie with C#
Here is the C# code used to this point:
SQLStatement = "select OBJECTID, Address, City, Region, Postal from MyAddresses";
SqlDataAdapter geoA = new SqlDataAdapter(SQLStatement, GEOconn);
DataSet GeoDS = new DataSet();
geoA.Fill(GeoDS, "records");
string geoAJSON = JsonConvert.SerializeObject(GeoDS);
Console.WriteLine("{0}", geoAJSON);
You can wrap your rows in another object with an "attributes" property using Json.Net's LINQ-to-JSON API.
In your code, replace this line:
string geoAJSON = JsonConvert.SerializeObject(GeoDS);
with this:
var obj = JObject.FromObject(GeoDS);
obj["records"] = new JArray(
obj["records"].Select(jo => new JObject(new JProperty("attributes", jo)))
);
string geoAJSON = obj.ToString();
Working demo here: https://dotnetfiddle.net/nryw27
Aside: based on your JSON it looks like you are storing postal codes in your database as decimals. Don't do that. They may look like numbers, but you should store them as strings. Postal codes in the US can have leading zeros, which will get dropped when you treat them as numbers. Some international postal codes can contain letters, so a numeric type won't even work in that case.
I have an array of complex JSON objects with embedded arrays of JSON objects. By way of an example, one JSON object might look like...
{
"shopID": "12194",
"name": "Shop Name",
"timeZone": "US\/Eastern",
"timeStamp": "2020-11-30T13:25:13+00:00",
"Contact": {
"contactID": "90",
"Addresses": [
"ContactAddress": {
"address1": "123 Some Street",
"address2": "",
"city": "A city",
"state": "A state",
"zip": "12345",
"country": "United States",
"countryCode": "US"
}
],
"Emails": "",
"Websites": {
"ContactWebsite": {
"url": "www.companyname.com"
}
}
},
"TaxCategory": {
"taxCategoryID": "2",
"isTaxInclusive": "false",
"tax1Name": "Tax region name",
"tax1Rate": "0.07"
}
}
I cannot modify the above format... I am calling a public API that is returning this as a response.
Assuming that the corresponding table schema has been created in Google BigQuery, how do I simply insert this JSON as a row in to the table?
My code looks like this...
bqc = BigQueryClient.Create("a-project-id");
var trShops = new TableReference()
{
ProjectId = "a-project-id",
DatasetId = "a-dataset-name",
TableId = "Shops"
};
# Call to my API data source that returns a JSON array of Shops...
content = await _lsrApiHelper.GetRawDataAsync(uri, currentOffset, _apiLimit);
# After call to API I deserialize the JSON response...
response = JsonSerializer.Deserialize<ShopResponseRoot>(content);
# Then I want loop through Shops in the List<ShopResponse> and insert them into BigQuery...
foreach (ShopResponse shop in response.Shop)
{
var newRow = new BigQueryInsertRow();
newRow.InsertId = "shopID";
newRow.Add(shop); # This is where I am struggling
bqc.InsertRow(trShops, newRow);
}
I am struggling with working out how to use a JSON or C# object to populate the data that I want inserting into BigQuery.
Any and all guidance greatly appreciated.
I have some issues using the Newtonsoft Json Plugin. I want to fill a datagridview using Json but dont know how. In the Documentation of Newtonsoft Json i get an exmaple with datatable but if i try this sample i just get Errors.
This is my Json:
[
{
"id": "17",
"name": "Filename",
"author": "unknown",
"size": "3.1MB",
"pfad": "ftp://path/Filename",
"Filetoken": "6747rzuzur6urzut766754677"
},
{
"id": "20",
"name": "Filename",
"author": "unknown",
"size": "3.1MB",
"pfad": "ftp://path/Filename",
"Filetoken": "6747rzuzur6urzut766754677"
}
]
I tried to use this example and this
Maybe anyone can help?
The JSON is an array, not an object, so deserialize it as a DataTable:
var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
Then add the DataTable to the DataGridView using this answer: Moving data from datatable to datagridview in C#.
What I am trying to do is print out the first index of an array in JSON format.
With the code:
storeInformation = myStoreInfoTable;
strResponseOutput = JsonConvert.SerializeObject(storeInformation);
These are the results:
[
{
"distance": 0,
"descr": "Toronto",
"address": "1300 Castlefield Avenue",
"city": "Toronto"
},
{
"distance": 7.1121883392,
"descr": "Etobicoke - North",
"address": "Resources Road",
"city": "Etobicoke"
}
]
What I tried to do to get the first index is:
storeInformationRow = dtbStoreInformation.Rows[0];
strResponseOutput = JsonConvert.SerializeObject(storeInformationRow);
What I get is:
{
"RowError": "",
"RowState": 2,
"Table": [
{
"distance": 0.0000000000,
"descr": "Toronto",
"address": "1300 Castlefield Avenue",
"city": "Toronto"
},
{
"distance": 7.1121883392,
"descr": "Etobicoke - North",
"address": "Resources Road",
"city": "Etobicoke"
}
]
}
The result I want is just
{
"distance": 0.0000000000,
"descr": "Toronto",
"address": "1300 Castlefield Avenue",
"city": "Toronto"
}
Help anybody?
I seems to me that the JSON serializer is goofing up because it doesn't know how to correctly serialize a DataRow. That's the only difference between the first and second snippet of code.
If you look at the MSDN documentation for the DataRow class you can see that the DataRow has the attributes displayed (RowError, RowState and Table) among many others.
To fix your problem I would suggest one of 2 options:
Create a new DataTable and add the DataRow you want to serialize to it, and call JsonConvert.SerializeObject() on that.
Map the columns (distance, descr, address & city) to another class (Store or something) and try to serialize that object. From what I read in the JsonConvert documentation it's possible (the class attributes are mapped correctly onto the JSON object).
Let me know how it goes!
you can just use :
var row = dtbStoreInformation.Rows[0];
string strResponseOutput = new {
distance = row[0].ToString(),
descr= row[1].ToString(),
address = row[2].ToString(),
city = row[2].ToString()}.ToJson();
don't forget the include of the namespace ServiceStack.Text
You can also create an anonym object
var obj = jsonString = new {
distance = row[0].ToString(),
descr= row[1].ToString(),
address = row[2].ToString(),
city = row[2].ToString()}
strResponseOutput = JsonConvert.SerializeObject(obj);