Newtonsoft Json Deserlize as C# Datagridview - c#

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#.

Related

How to modify the JSON obtained from serializing a DataSet using Json.Net for purposes of ESRI geocoding

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.

Newtonsoft Serialize the List of Objects

Is there a way to generate Serialized string of List <object> without any [ ]
we are doing serialization using following code
JsonConvert.SerializeObject(data)
[
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "X"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "Y"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "Z"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "XY"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "XYZ",
"Payload": "X>>1"
}
]
Is there a way to remove above [ and ] , I have workaround to call Trim('[') and Trim(']') on serialize string. Is there any setting that come out of box from NewtonSoft which removes [ and ], also I dont want to make use of anonymous object.
No there's no way, if data is a collection then JsonConvert will return a JSON array. You can as you stated modify the output string by using Trim('[').Trim(']') but your JSON won't be valid.
You're trying to use a List, not a Map/Dictionary, but you don't want the array behavior that comes with a List (but not a Dictionary/Map).
Get these straight and you'll find data MUCH easier to work with in many programming languages ;)
https://stackoverflow.com/a/4131714/901899

Need to convert JSON to datatable

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.

DataContractJsonSerializer - deserialize to dictionary

I want to deserialize a json that I get as result of a REST query (the json string can not be changed) to a dictionary type.
The json string looks something like this:
{
"collection": {
"useful": true
"attributes": {
"ObjectID": "ObjectID",
"Name": "Name",
"FirstID": "FirstID",
"LastID": "LastID",
"Count": "5",
},
"Type": "Polyline",
"features": [{
"attributes": {
"length": 0.10879009704943393
"time": 0.3822371137674949,
"text": "some text",
"ABC": -2209161600000,
"Type": "SomeType"
}
}]
}
}
I create boolean property for 'useful' and integer for 'count' etc. but I have a problem with the 'attributes'. As you can see, in each section (and per result) I get different 'attributes'.
I need to deserialize them into some generic collection like dictionary or list of KeyValuePair. the problem is, as stated in msdn (here - http://msdn.microsoft.com/en-us/library/bb412170.aspx) "Dictionaries are not a way to work directly with JSON".
How can I do it if so?
My application is silverlight 5, .Net 4, VS 2010.
Thanks in advance!

Consuming JSON Web Data into a Class Array in C# .Net

I'm having a few problems trying to consume my JSON Data from a web URL and put it into my Class Array.
My class looks something like this;
public class User
{
String Name;
String Serial;
String Email;
}
Where my JSON data looks like
{ "name": "cname", "value": [ "Joe Bloggs"] },
{ "name": "serialnumber", "value": [ "231212312" ] },
{ "name": "gender", "value": [ "male" ] },
{ "name": "email", "value": [ "jbloggs#domain.com" ] },
I want to pop this into a User Class Array so that it would be somthing like
User myUsers[] = new User[100];
I have the data downloaded using a StreamReader, but I'm lost as to where to start. I've tried out DataContractJsonSerializer and a few others but can't find any basic guides on the web where to start.
I should note that I want to only grab the values listed in the class and not extras such as Gender etc.
If someone could provide a basic sample of both the class and the program implementation to read the data that would be great.
Thanks,
CM888.
I Highly Reccomend looking into this library:
Json.NET
It has many great features, but the best is that it's designed to mimic LINQ to XML. You can use it very similarly.
Using this library you could parse your json into objects and work with them & linq queries to build up your user array.
To expand on my comment above: (Unrelated to question or answer)
What i meant was i was curious why your JSON wasn't strctured like this:
[
{"cname": "Joe Bloggs", "serialnumber": "231313213", "gender": "male", "email": "jbloggs#domain.com"},
{"cname": "Another Dude", "serialnumber": "345345345", "gender": "male", "email": "another#dude.com"}
]

Categories