How do I deserialize a Json object? - c#

This is the code I use to deserialize JSON.But when I try writing it in console, it says "System.Collections.Generic.Dictionary`2[System.String, System.Object]"
System.Net.WebClient wc = new System.Net.WebClient();
string Jayson = wc.DownloadString("http://api.urbandictionary.com/v0/define?term=api");
object obj = JsonHelper.Deserialize(Jayson);
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(Jayson);
Console.WriteLine(values);
How do I deserialize it and extract only the "definition" from the JSON?

You can create some concrete types to map to and deserialize using those rather than more generic types, for example:
public class Result
{
[JsonProperty("definition")]
public string Definition { get; set; }
[JsonProperty("author")]
public string Author { get; set; }
[JsonProperty("permalink")]
public string PermaLink { get; set; }
}
public class Results
{
[JsonProperty("list")]
public List<Result> List { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; }
}
Then:
var results = JsonConvert.DeserializeObject<Results>(json);
You can then iterate the definitions:
foreach(var result in results.List)
Console.WriteLine(result.Definition);
Json.NET will ignore the other properties it can't map so you can add/remove them as needed.

You're getting "System.Collections.Generic.Dictionary`2[System.String, System.Object]" because Console.WriteLine can only write strings and it doesn't know how to turn a dictionary into a string.
To print all the entries, loop over the collection and print each entry:
System.Net.WebClient wc = new System.Net.WebClient();
string Jayson = wc.DownloadString("http://api.urbandictionary.com/v0/define?term=api");
object obj = JsonHelper.Deserialize(Jayson);
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(Jayson);
foreach(var entry in values)
{
Console.WriteLine($"{entry.Key} : {entry.Value}");
}

Just parse your json string to a JObject and then get the "defenition" property from it
jObj = JObject.Parse("yourJsonString");
string defenition = jo["definition"];

Related

accessing dictionary from a Json string in c#

I have a JSON string as a response from server which contains key value pairs like dictionary. Some of the keys can have dictionary as their values as well. I have to access values based on certain keys from the inner dictionary. How can i access them and store in a string?
Something like this:-
string JsonData = "{\"status\":\"BAD_REQUEST\",\"code\":400,\"errorsCount\":1,\"errors\":[{\"desciption\":\"Field cannot be blank\"}]}";
string toBeAccessedValue = Field cannot be blank;
Any help would be appreciated.
You can use [JsonExtensionData] to deserialize your json to class object.
public class RootObject
{
[JsonExtensionData]
public Dictionary<string, JToken> data { get; set; }
}
And you can use above class like
RootObject ro = JsonConvert.DeserializeObject<RootObject>(JsonData);
var errors = ro.data["errors"].ToObject<JObject[]>();
string description = errors.FirstOrDefault().Property("desciption").Value?.ToString();
Console.WriteLine("description: " + description);
Console.ReadLine();
Alternative:
You can use below class structure that can be helpful to you to deserialize your json and retrieve any value that you want.
public class Error
{
public string desciption { get; set; }
}
public class RootObject
{
public string status { get; set; }
public int code { get; set; }
public int errorsCount { get; set; }
public List<Error> errors { get; set; }
}
And you can use above class structure to deserealize your json like
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(JsonData);
string description = rootObject.errors.FirstOrDefault()?.desciption;
Console.WriteLine("description: " + description);
Console.ReadLine();
Edit:
If you want to deserialize your json with JavaScriptSerializer then.
JavaScriptSerializer serializer = new JavaScriptSerializer();
RootObject rootObject = serializer.Deserialize<RootObject>(JsonData);
string description = rootObject.errors.FirstOrDefault()?.desciption;
Console.WriteLine("description: " + description);
Console.ReadLine();
Output:

How to parse a JSON string in to a name value pair in C#

I have to parse the JSON string in to a name value pair list :
{"vars":[
{"name":"abcd","value":"true"},
{"name":"efgh","value":"false"},
{"name":"xyz","value":"sring1"},
{"name":"ghi","value":"string2"},
{"name":"jkl","value":"num1"}
],"OtherNames":["String12345"]}
I can not add the reference of newtonsoft JsonConvert due to multiple parties involved .
With JavaScriptSerializer i am able to get the json converted to name value only when i have one value in the string but not an array
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
Dictionary<string,string> dict = jsSerializer.Deserialize<Dictionary<string, string>>(jsonText);
I think the declaration which says i will get the array values is missing somewhere.
You can't deserialize that Json as Dictionary<string, string>. Because the json contains two different array and you should use complex object to deserialize it like this;
public class Var
{
public string name { get; set; }
public string value { get; set; }
}
public class SampleJson
{
public List<Var> vars { get; set; }
public List<string> OtherNames { get; set; }
}
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var sampleJson = jsSerializer.Deserialize<SampleJson>(jsonText);

Deserialize JSON result

I have developed service which returns JSON data as below
{"names":["Name1","Name2","Name3","Name4"],"validname":false}
Now i want to deserialize it in c#.
I have tried with below methods, but still getting error
Dictionary<string, string[]> lst = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(result);
Can anyone please help me
class SomeClass
{
public string[] Names { get; set; }
public bool Validname { get; set; }
}
and then
var items = JsonConvert.DeserializeObject<SomeClass>(result);
also you can use JsonProperty attribute to map properties to json like so
[JsonProperty("names")]
public string[] MyPropertyNamedSomethingDifferent { get; set; }

Loop trought Dictionary<string, object> only for a key in c#

I have a dictionary of strings and object that i obtained deserializing this json answer:
{"labels":[{"id":"1","descrizione":"Etichetta interna","tipo":"0","template_file":"et_int.txt"},{"id":"2","descrizione":"Etichetta esterna","tipo":"1","template_file":"et_ext.txt"}],"0":200,"error":false,"status":200}
using the code:
var labels = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
Now i want to loop only trought the objects inside the "labels" key.
I tried
foreach (var outer in labels["labels"]){/* code */}
but i got error:
CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'.
Solved replacing the dictionary with a class, thank you
Create a class to deserialize your json:
To create classes, you can copy the json in clipboard and use the
Edit / Paste special / Paste JSON as class
in visual studio (I use vs2013).
[TestMethod]
public void test()
{
string json = "{\"labels\" : [{\"id\" : \"1\",\"descrizione\" : \"Etichetta interna\",\"tipo\" : \"0\",\"template_file\" : \"et_int.txt\"}, {\"id\" : \"2\",\"descrizione\" : \"Etichetta esterna\",\"tipo\" : \"1\",\"template_file\" : \"et_ext.txt\"}],\"0\" : 200,\"error\" : false,\"status\" : 200}";
var root = JsonConvert.DeserializeObject<Rootobject>(json);
foreach (var label in root.Labels)
{
//Use label.Id, label.Descrizione, label.Tipo, label.TemplateFile
}
}
public class Rootobject
{
public Label[] Labels { get; set; }
public int _0 { get; set; }
public bool Error { get; set; }
public int Status { get; set; }
}
public class Label
{
public string Id { get; set; }
public string Descrizione { get; set; }
public string Tipo { get; set; }
public string TemplateFile { get; set; }
}
You need to loop through your dictionary.
foreach(KeyValuePair<string, Object> entry in labels)
{
// do something with entry.Value or entry.Key
}
Once you start looping through it you will get access to key and value. Since you are interested to look at entry.value you can do operation on that easily. Currently your dictionary value is type of object which does not have an enumerator
Your problem is that you've defined the Type of Value for each dictionary entry as object. C# can't know how to loop over on object. So you need to work out what type is actually inside the object once the JavaScriptSerializer have parsed the JSON. One way is
var t = typeof(labels["labels"]);
Once you know what type the serializer is creating, all you need to do is cast the object back to that type. For example, assuming it's a list of objects
var labels = (List<object>)labels["labels"];
foreach (var label in labels)
{
}
Alternatively, if each object in the JSON is the same, you could try create the dictionary as the type you need. So you serializing becomes
var labels = new JavaScriptSerializer()
.Deserialize<Dictionary<string, List<object>>>(json);
A possible solution:
static void Main(string[] args) {
string json = #"{'labels':[{'id':'1','descrizione':'Etichetta interna','tipo':'0','template_file':'et_int.txt'},{'id':'2','descrizione':'Etichetta esterna','tipo':'1','template_file':'et_ext.txt'}],'0':200,'error':false,'status':200}";
var labels = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
IEnumerable inner_labels = labels["labels"] as IEnumerable;
if (inner_labels != null) {
foreach (var outer in inner_labels) {
Console.WriteLine(outer);
}
}
}
Otherwise, you can create a class with deserialization information and instruct the deserializer to deserialize your json string to that type:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
[Serializable]
public class JsonData {
[XmlElement("labels")]
public List<JsonLabel> labels { get; set; }
[XmlElement("0")]
public int zero { get; set; }
[XmlElement("error")]
public bool error { get; set; }
[XmlElement("status")]
public int status { get; set; }
}
[Serializable]
public class JsonLabel {
[XmlElement("id")]
public int id { get; set; }
[XmlElement("descrizione")]
public string descrizione { get; set; }
[XmlElement("tipo")]
public int tipo { get; set; }
[XmlElement("template_file")]
public string template_file { get; set; }
}
class Program {
static void Main(string[] args) {
string json = #"your json string here...";
var jsonData = new JavaScriptSerializer().Deserialize<JsonData>(json);
foreach (var label in jsonData.labels) {
Console.WriteLine(label.id);
}
}
}
Could you please try below snippet?
It might be help you.
foreach (var item in labels["labels"] as ArrayList)
{
Console.Write(item);
}

Parsing Json facebook c#

I am trying for many hours to parse a JsonArray, I have got by graph.facebook, so that i can extra values. The values I want to extract are message and ID.
Getting the JasonArry is no Problem and works fine:
[
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_1\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the first message\",
\"created_time\":\"2011-11-04T21:32:50+0000\"}"},
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_2\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the second message\",
\"created_time\":\"2012-01-03T21:05:59+0000\"}"}
]
Now I have tried several methods to get access to message, but every method ends in catch... and throws an exception.
For example:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
Console.WriteLine(item.body.message);
}
throws the exception: System.Collections.Generic.Dictionary doesnt contain definitions for body. Nevertheless you see in the screenshot below, that body contains definitions.
Becaus I am not allowed to post pictures you can find it on directupload: http://s7.directupload.net/images/120907/zh5xyy2k.png
I don't havent more ideas so i please you to help me. I need this for a project, private, not commercial.
Maybe you could give me an phrase of code, so i can continue my development.
Thank you so far
Dominic
If you use Json.Net, All you have to do is
replacing
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
with
dynamic result = JsonConvert.DeserializeObject(json);
that's all.
You are not deserializing to a strongly typed object so it's normal that the applications throws an exception. In other words, the deserializer won't create an Anynymous class for you.
Your string is actually deserialized to 2 objects, each containing Dictionary<string,object> elements. So what you need to do is this:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(s);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
Here's a complete sample code:
void Main()
{
string json = #"[
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_1"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the first message"",
""created_time"":""2011-11-04T21:32:50+0000""}},
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_2"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the second message"",
""created_time"":""2012-01-03T21:05:59+0000""}}
]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
}
Prints:
This is the first message
This is the second message
I am using this simple technique
var responseTextFacebook =
#"{
"id":"100000891948867",
"name":"Nishant Sharma",
"first_name":"Nishant",
"last_name":"Sharma",
"link":"https:\/\/www.facebook.com\/profile.php?id=100000891948867",
"gender":"male",
"email":"nihantanu2010\u0040gmail.com",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2013-06-10T07:56:39+0000"
}"
I have declared a class
public class RootObject
{
public string id { get; set; }
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string link { get; set; }
public string gender { get; set; }
public string email { get; set; }
public double timezone { get; set; }
public string locale { get; set; }
public bool verified { get; set; }
public string updated_time { get; set; }
}
Now I am deserializing
JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();
RootObject parsedData = objJavaScriptSerializer.Deserialize<RootObject>(responseTextFacebook );

Categories

Resources