DataContractJsonSerializer - deserialize to dictionary - c#

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!

Related

How to access inner properties of a Json Object?

I am learning C# and I am trying to parse json/xml responses and check each and every key and value pair. For xml I am converting to json so I have only one function/script to work with both cases. My issue is that I am working with a wide range of json responses which are not similar and there may be arrays in some of the json response. I have tried accessing the "Count" of the json object as a way to check for arrays.
Note: The responses will vary. This example is for Products > Product > name, quantity and category. The next response will change and can be like Country > State > Cities and so on. I cannot rely on creating classes since all responses are going to be different. Plus I am working on automating it so it should be able to handle anything thrown at it.
Sample Json I am working with:
{
"products": {
"product": [
{
"name": "Dom quixote de La Mancha",
"quantity": "12",
"category": "Book"
},
{
"name": "Hamlet",
"quantity": "3",
"category": "Book"
},
{
"name": "War and Peace",
"quantity": "7",
"category": "Book"
},
{
"name": "Moby Dick",
"quantity": "14",
"category": "Book"
},
{
"name": "Forrest Gump",
"quantity": "16",
"category": "DVD"
}
]
}
The way I am accessing the count, name and value is as follows:
dynamic dyn = JsonConvert.DeserializeObject<dynamic>(jsonText);
foreach (JProperty property in dyn.Properties())
{
string propname = property.Name;
var propvalue = property.Value;
int count = property.Count;
}
Is there a way to access these without going through the foreach loop like int count = dyn.Count ? All I am getting from this is null instead of actual values.
For the above example my end result will be like:
This responses contains products> product> 5 x (name, quantity, category)
The QuickWatch for the object:
QuickWatch for dyn object
Try to deserialize your JSON into JObject like below:
var jObject = JsonConvert.DeserializeObject<JObject>(jsonText);

How to deserialize from a JSON-RPC websocket api response to the correct static type

The only way I could figure out what the JSON response could be deserialized to was to look for strings within the JSON to give me a hint on what it could be. This seems very hacky and hoping there is a better way.
Given the 2 example JSON responses, how would I deserialize to the proper static type?
The result field could contain any simple or complex type.
In the first example results would be a list of names and the second would be a list of prices.
{
"jsonrpc": "2.0",
"id": 1,
"result": [ "Jane Doe", "Joe Smith" ]
}
{
"jsonrpc": "2.0",
"id": 1,
"result": [ 123, 456 ]
}

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

JsonConvert.DeserializeObject omit bracket

string myString ="{\"val\":{\"id\":1,\"name\":\"lua\"}}";
dynamic json = JsonConvert.DeserializeObject(myString);
so
json ={{
"attributes": {
"id": 1,
"name": "lua"}
}}
something like this.
but i want to make json just like this:
[{
"attributes": {
"id": 1,
"name": "lua"}
}]
How can i do that in C# using Json.Convert or another way?

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