Deserializing Json with numbered keys in ServiceStack - c#

I have such Json:
{
data:{
"50":{"id":"50","name":"test", etc...},
"51":{"id":"51","name":"test", etc...},
"53":{"id":"53","name":"test", etc...},
...
}
}
What is the correct way to deserialize this Json?
[UPDATED]
I think I must to adjust my question. Is it possible to parse Json using class with description of objects. E.g. I have such class and Json which I parse with .FromJson():
public class Data
{
public ...
}
public class Category
{
public int Id{get;set;}
public string Name{get;set;}
}
What should be instead three dots?

Your json contains an object O. This object has a member data that is a dictionary from strings or ints to your category objects. So try something like:
class Root
{
public Dictionary<int, Category> data;
}
var o = JavaScriptSerializer.Deserialize<Root>(json);

If you are using servicestack.text just do
var v = myJson.FromJson();
Don't forget that servicestack is best used when serialization also made with servicestack.

the best way to deserialize Json object to c# class in JSON.NET project (found on codeplex)
the deserialize example is:
JsonConvert.DeserializeObject<Category>(jsonString);

Related

Deserialize JSON object containing array to C# object

This is my JSON string:
{"type":"motor","ids":["1","2","5","7","8","10"]}
And this is the object I want to generate from it:
public class ElementArray {
public ElementType type;
public String[] ids;
public ElementArray() {
}
}
How can I achieve that? I googled about Json.NET, but they only explain how to deserialize an array but not how to deserialize an object containing an array as a field (see my class above).
What I tried is
JavaScriptSerializer jss = new JavaScriptSerializer();
ElementArray elements = jss.Deserialize<ElementArray>(strJson);
but when I debug the code, the field ids contains null.
IMO simplest way to deal with json is using newtonsoft.json library
http://www.newtonsoft.com/json
And here is example how to deserialize object:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm

Deserialize object with DataContractJsonSerializer and map it to a list

I'm already knew how to deserialize a JSON array using DataContractJsonSerializer, but now I have a JSON object, it has a key called items and the value is an array.
for example, the JSON string is { name: "someString", items: [1, 2, 3] }
Now I want to know is there any built-in method to convert this object to a custom class derived from List<T>, for example to the following class:
[DataContract] // This is not working, you can't apply DataContract attribute to a List<T>
// [ItemsCollectionIsIn("items")]
public class MyObject : List<int>
{
[DataMember]
public string name;
}
I had tried [CollectionDataContract] attribute with its ItemName set to "items", but seems DataContractJsonSerializer just ignores ItemName property and serializes/deserializes the object to/from an array.
Now I can implement IList<T> on my class and return values from a internal list, or I think I can write one class for JSON object contract and the other one derived from List then populate values manually, is there any better ways?
I'm working on Windows Phone LongListSelector so I need a GroupedList (List<List<T>>).
Or if JSON.Net can do it more easier please give me some hint.
I think you modeled your type incorrectly, the array is a property in the root object. Try it this way:
[DataContract]
public class MyObject
{
[DataMember]
public string name;
[DataMember]
public List<int> items;
}

Deserialization of not so well formated json

I need help or some inspiration for some strange json deserialization.
This is the json I recieve from a service (can't change it, its an external service):
{
"status":"OK",
"statuscode":200,
"payload":{
"solarforecast":{
"5876":{
"2014-06-06 23:00:00":{
"bh":0,
"dh":0
},
"2014-06-07 00:00:00":{
"bh":0,
"dh":0
},
[...]
}
}
}
I made a call to get values for a object with id 5876.
So if I made a call for object with id 1254, the json changed this way:
[...]
"solarforecast":{
"1254":{
"2014-06-06 23:00:00":{
[...]
I now want to create an c# object from this json code with help of Newton ;) .
My frist Problem is that the property name (aka object id) is different for any object call and its a number.
My second problem are the sub objects with undefinded count. I think in a well formed json object it has to be somethink like this (see "[" brackets):
"solarforecast":{
"5876":[
"2014-06-06 23:00:00":{
"bh":0,
"dh":0
},
"2014-06-07 00:00:00":{
"bh":0,
"dh":0
},
[...]
]
}
Has anybody a trick or solution how to well deserialize this json into a proper c# class?
I try to get somethink like that as result:
public class Payload
{
[JsonProperty("solarforecast")]
public SolarForecast SolarForecast;
}
public class SolarForecast
{
[JsonProperty("???")]
public IEnumerable<SolarForecastTimeSet> SomeObjectID;
}
public class SolarForecastTimeSet
{
[JsonProperty("???")]
public decimal TimeStamp;
[JsonProperty("dh")]
public decimal DiffusRadiationHorizontal;
[JsonProperty("bh")]
public decimal DirectRadiationHorizontal;
}
Thanks for your help!!
Steffen
Ok figured out how it will work!
Object tree has to be:
public class Payload
{
[JsonProperty("solarforecast")]
public Dictionary<int, Dictionary<DateTime, SolarForecastTimeSet>> SolarForecast;
}
public class SolarForecastTimeSet
{
[JsonProperty("dh")]
public decimal DiffusRadiationHorizontal;
[JsonProperty("bh")]
public decimal DirectRadiationHorizontal;
}
Thanks #andyp for his dictionary hint!

Deserialize JSON data

I've got a JSON data from Twitter API SEARCH.
I'm trying to deserialize these data into objects.
The JSON scheme looks like this:
{
"element": INT,
"element2": STRING,
..
..
"Results":[
{
"user":STRING,
"image":STRING,
..
..
}
]
}
How could I deserialize those JSON elements into objects using JSON Toolkit or something else?
Create a class that matches the JSON schema
public class Data
{
public string Element{get;set;}
public string Element2{get;set;}
public List<Result> Results{get;set;}
}
public class Result
{
public string User{get;set;}
public string Image{get;set;}
}
and use JSON.NET to deserialize
var result = JsonConvert.DeserializeObject<Result>(json);
If you have problems with correct type definition, you can always use dynamic deserialization using Json.Net:
var original = JsonConvert.DeserializeObject<dynamic>(jsonstring);
and then build your desired object based on it (if for example the original one contains overhead information set, and you don't need all of them):
var somepart = new {
E1 = original.element1,
E2 = original.element2
};

How to map a data contract to refer to correct fields in a JSON object?

I'm recieving a JSON object that looks like the example below.
{
"name1":{"name1a":"value1a","name1b":"value1b"},
"name2":{"name2a":"value2a","name2b":"value2b"}
}
I've set up a data contract for it (since I only need to access a single data field at the moment) like this.
[DataContract]
public class MyThingy
{
[DataMember(Name="name1b")]
public string Name1b { get; set; }
public MyThingy() { }
public MyThingy(String name1b)
{
Name1b = name1b;
}
}
When I've serialized the object, I try to print it out (which works, since I'm getting a string description of the class) and them the field Name1b. The last part doesn't work and I'm getting null there. My guess is that I must have mapped the data contract wrongly but I can't see how to correct it.
How should the MyThingy class be declared?
My JSON object is fetched as described in this post.
I would use JavaScriptSerializer here,
string json = #"{
""name1"":{""name1a"":""value1a"",""name1b"":""value1b""},
""name2"":{""name2a"":""value2a"",""name2b"":""value2b""}
}";
var obj = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, string>>>(json);
Console.WriteLine(obj["name1"]["name1b"]);
You can also use Json.Net and dynamic together
dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.name1.name1b);

Categories