Deserialize JSON data - c#

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

Related

How do i deserialize a json to an object? My attemts end up with an JObject and not an object with my properties. How do i avoid this?

I want to convert something like this this {\"ref\":\"/my/path\",\"action\":\"set\",\"payload\":\"\"}
into a generic object in C#. What i tried is this
object mess1 = JObject.Parse(message);
dynamic mess2 = JsonConvert.DeserializeObject<object>(message);
dynamic mess3 = JValue.Parse(message);
The expected result would be an object with the properties ref, action and set. The actual result is an object containing the JObject
ChildrenTokens
Count
First
HasValues
Last
Next
Parent
...
these are not part of my object. What is the correct way of doing this?
The payload in this message is a string OR an arbitrary object. The payload is to be written to a database and i do not care what it contains.
JObject.Parse generates a JObject instance. You can do this a couple of ways, if you already have JObject, you can do the following:
var obj = JObject.Parse(json);
var command = obj.ToObject<Command>();
Or, you can work from the string:
var command = JsonConvert.Deserialize<Command>(json);
We generally use
this method
public static JObject JsonParsed(string Json)
{
return JObject.Parse(Json);
}
You can deserialize it into a dynamic object with:
dynamic parsed = JObject.Parse("ref\":\"/my/path\",\"action\":\"set\",\"payload\":\"\");
And access your properties like any other object:
Console.WriteLine(parsed.ref); // "/my/path/"
Console.WriteLine(parsed.action); // "set"
Console.WriteLine(parsed.payload); // "\"
By "object with my properties" you mean what's often referred as POCO.
You have to define a POCO object like so:
public class Poco
{
public string Ref { get; set; }
public string Action { get; set; }
public string Payload { get; set; }
}
Then deserialize your JSON like so:
string json = "{'ref':'/my/path','action':'set','payload':''}";
Poco myPoco = JsonConvert.DeserializeObject<Poco>(json);
Now you will have myPoco.Ref, myPoco.Action, myPoco.Payload properties populated from your JSON.

NewtonSoft Json retrieve data with brackets method

Currently I am using the YouTube API to get some data. The data is in json and I am trying to get a single part of it.
The problem that I am facing right now is that I want to use the following method:
WebClient client = new WebClient();
string jsonData = client.DownloadString("https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&part=contentDetails&key=");
var results = JsonConvert.DeserializeObject(jsonData);
string duration = results["items"]["contentDetails"]["duration"];
Currently this results in an error:
Cannot apply indexing with [] to an expression of type 'object'
The problem I am facing right now is that I don't know how to deserialize the object properly so I can use text indexes to get to the data. I used to do it like this before but I can't recall it and can't find anything about my method.
What you should do is define a class with all your properties that matches your JSON, and then pass that class as a type argument to the deserialization:
Results results = JsonConvert.DeserializeObject<Results>(jsonData);
I don't have more info about your JSON, but a quick definition would look like this:
public class Results
{
public Items items { get; set; }
}
public class Items
{
public ContentDetails contentDetails { get; set; }
}
public class ContentDetails
{
public string duration { get; set; }
}
If you need help converting a JSON response to C# classes, you can use converters such as http://json2csharp.com/
You can also deserialize to a dynamic type, like so:
var results = JsonConvert.DeserializeObject<dynamic>(jsonData);
Then, you just access your properties:
string duration = results.items.contentDetails.duration;
However, using dynamic is not recommended most of the time, because it effectively removes static typing, so you must be sure that duration will be a string, or it will throw a runtime exception when you try to access it.
Normally if I'm dealing with a JSON payload that I don't feel like mapping to a strong type I use JObjects which allow for LINQ to JSON.
var jObject = JObject.Parse(jsonString);
This will allow the properties of the object to be indexed using [] syntax.
More information on using LINQ to JSON in the API docs.
Get your Deserialized data into dynamic type:
dynamic results = JsonConvert.DeserializeObject(jsonData);
and then access it using .:
string duration = results.items.contentDetails.duration;
The syntax you're using is used in javascript.
Try this way:
dynamic results = JsonConvert.DeserializeObject(jsonData);
then you can do
string duration = results["items"]["contentDetails"]["duration"];
or
string duration = results.items.contentDetails.duration;
Reference to dynamic keyword on MSDN: https://msdn.microsoft.com/en-us/library/dd264736.aspx

Deserialize raw JSON and convert to custom C# Object

I have the following raw JSON string:
[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]
I have tried the following without luck:
My custom object class:
public class MyObject
{
public string msg { get; set; }
public string id { get; set; }
public string chn { get; set; }
}
JSON string:
string str = "[\"Hello World!\",\"94952923696694934\",\"MyChannel\"]";
1st attempt at deserilization using System.Web.Script.Serialization:
JavaScriptSerializer serializer = new JavaScriptSerializer();
MyObject obj1 = serializer.Deserialize<MyObject>(str);
2nd attempt at deserilization using Newtonsoft.Json:
MyObject obj2 = JsonConvert.DeserializeObject<MyObject>(str);
Both attempts fail. Any suggestions?
You have a JSON array of strings, not an object with property names.
So the best you can do here is to deserialize the array:
IEnumerable<string> strings =
JsonConvert.DeserializeObject<IEnumerable<string>>(str);
...then use the resulting sequence strings as you see fit.
With PubNub, you can just pass in the native String, Dictionary, or Array, and we'll JSON encode it for you on the publish side, and auto JSON decode for you on the subscriber side.
It's because your 'custom object' isn't equivalent to the json representation. The json you're deserializing is just a string[] in C# (you can also use List<string> or other IEums).
So in code you're looking for;
string[] theJson = JsonConvert.DeserializeObject<string[]>(str);
MyObject would be used for the following json;
{
"msg":"Hello World!",
"id":"94952923696694934",
"chn":"MyChannel"
}

Deserializing Json with numbered keys in ServiceStack

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

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