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"
}
Related
I m working with Core Web API and I have the challenge to nest different class objects into an ArrayList and send them over the FromBody object, the issue is I have to pack them in a way that on the receiving side I deserialize them into their respective objects.
an example is below.
[Serializable]
public class M1
{
public string Name { get; set; }
public int Age { get; set; }
}
[Serializable]
public class M2 : M1
{
public string Gender { get; set; }
public int Height { get; set; }
}
static void Main(string[] args)
{
try
{
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
//Method1
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(alist, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Method 2
try
{
result = Newtonsoft.Json.JsonConvert.SerializeObject(mObj, Formatting.Indented);
result = result + Newtonsoft.Json.JsonConvert.SerializeObject(m2Obj, Formatting.Indented);
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(result);
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
For the first method its throwing error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SerliazeDeserliaze.M1' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array of a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
for the second method, it says
Additional text encountered after finished reading JSON content: {. Path '', line 4, position 2.
By doing some hack I have done that different way.
M1 mObj = new M1();
M2 m2Obj = new M2();
ArrayList alist = new ArrayList();
ArrayList alistb = new ArrayList();
mObj.Name = "Apple";
mObj.Age = 20;
m2Obj.Name = "Banana";
m2Obj.Age = 30;
m2Obj.Gender = "Male";
m2Obj.Height = 6;
alist.Add(mObj);
alist.Add(m2Obj);
string result = string.Empty;
M1 mObjD = new M1();
M2 mObj2D = new M2();
string json = JsonConvert.SerializeObject(alist, Formatting.Indented, new KeysJsonConverter(typeof(ArrayList)));
alistb= JsonConvert.DeserializeObject<ArrayList>(json, new KeysJsonConverter(typeof(ArrayList)));
mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<M1>(alistb[0].ToString());
mObj2D = Newtonsoft.Json.JsonConvert.DeserializeObject<M2>(alistb[1].ToString());
Serializing the list into JSON and then Deserializing it in a reverse way get the job done.
If you serialize list of object, you should deserialize it also into list:
string result = Newtonsoft.Json.JsonConvert.SerializeObject(aList, Formatting.Indented);
List<M1> mObjD = Newtonsoft.Json.JsonConvert.DeserializeObject<List<M1>>(result);
JSON supports the following two data structures,
Collection of name/value pairs - This Data Structure is supported by different programming languages.
Ordered list of values - It includes an array, list, vector or sequence, etc.
JSON has the following styles,
Object
An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example,
var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}
Array
Value order set. An array begins with "[" and end with "]". And values are separated with commas. For example,
var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},
{"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]
String
Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.
var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"
We can implement JSON Serialization/Deserialization in the following three ways:
Using JavaScriptSerializer class
Using DataContractJsonSerializer class
Using JSON.NET library
Using DataContractJsonSerializer
DataContractJsonSerializer class helps to serialize and deserialize JSON.
It is present in namespace System.Runtime.Serialization.Json which is
available in assembly System.Runtime.Serialization.dll. Using the
class we can serialize an object into JSON data and deserialize JSON
data into an object.
Let's say there is Employee class with properties such as name, address, and property values also assigned. Now we can convert the Employee class instance to the JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.
Let's create a custom class BlogSite for serialization and deserialization,
[DataContract]
class BlogSite
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and create an instance of MemoryStream class to write object(BlogSite). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
BlogSite bsObj = new BlogSite()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));
MemoryStream msObj = new MemoryStream();
js.WriteObject(msObj, bsObj);
msObj.Position = 0;
StreamReader sr = new StreamReader(msObj);
// "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}"
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
C# Deserialization
In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of BlogSite class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and creating an instance of MemoryStream class to write an object(BlogSite). Lastly, it creates an instance of StreamReader class to read JSON data from MemorySteam object.
string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}";
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));
BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);
Response.Write("Name: " + bsObj2.Name); // Name: C-sharpcorner
Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge
}
C# Using JavaScriptJsonSerializer
JavaScriptSerializer is a class that helps to serialize and deserialize JSON. It is present in the namespace System.Web.Script.Serialization is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use the Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.
Following code, a snippet is to declare a custom class of BlogSites type.
class BlogSites
{
public string Name { get; set; }
public string Description { get; set; }
}
C# Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Serializing object to json data
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(bsObj); // {"Name":"C-sharpcorner","Description":"Share Knowledge"}
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.
// Deserializing json data to object
JavaScriptSerializer js = new JavaScriptSerializer();
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);
string name = blogObject.Name;
string description = blogObject.Description;
// Other way to whithout help of BlogSites class
dynamic blogObject = js.Deserialize<dynamic>(jsonData);
string name = blogObject["Name"];
string description = blogObject["Description"];
C# Using Json.NET
Json.NET is a third-party library that helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open-source software and free for commercial purposes.
The following are some awesome features,
Flexible JSON serializer for converting between .NET objects and JSON.
LINQ to JSON for manually reading and writing JSON.
High performance, faster than .NET's built-in JSON serializers.
Easy to read JSON.
Convert JSON to and from XML.
Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Let’s start learning how to install and implement:
In Visual Studio, go to Tools Menu -> Choose Library Package Manager -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.
Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manager Solution and type “JSON.NET” to search it online. Here's the figure,
Json.NET
Serialization
In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then it calls static method SerializeObject() of JsonConvert class by passing object(BlogSites). It returns JSON data in string format.
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "C-sharpcorner",
Description = "Share Knowledge"
};
// Convert BlogSites object to JOSN string format
string jsonData = JsonConvert.SerializeObject(bsObj);
Response.Write(jsonData);
C# Deserialization
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
string json = #"{
'Name': 'C-sharpcorner',
'Description': 'Share Knowledge'
}";
BlogSites bsObj = JsonConvert.DeserializeObject<BlogSites>(json);
Response.Write(bsObj.Name);
JSON.NET, visit here.
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the
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.
Following is my json string:
[
{"Sname":"wordpress_Site_Url","Settings":"http://www.mywebsite.com","lab":false},
{"Sname":"wordpress_template","Settings":"[vc_row][vc_column width="2/3"][vc_column_text] {{{description}}} [/vc_column_text][/vc_column][vc_column width="1/3" css=".vc_custom_1438623014033{border-color: #dbead5 !important;}"] [gravityform id="14" title="false" description="false" ajax="true" field_values="downloadFileID={{downloadURL}}"][/vc_column][/vc_row][vc_row][vc_column][vc_column_text] [/vc_column_text][/vc_column][/vc_row]","lab":true,"selected":false},
{"Sname":"dummy","Settings":"abc","lab":false},
{"Sname":"testing","Settings":"ssds","lab":false}
]
I want to write a function that takes key Sname in json above as parameter and return the value Setting in json above from this json string.
Escaping doesn't help, before deserializing
If you have influence on the way how the Settings object is serialized I would recommend you to serialize it properly. Otherwise you would have to do awful things to get it to work. Something like:
class MyResultClass
{
public string Sname { get; set; }
public string Settings { get; set; }
}
private MyResultClass Convert(string str)
{
var newStr = str.Replace("\"Settings\"", "VERYUNIQUEKEYWORD")
.Replace("\"Sname\"", "ANOTHERKEYWORD")
.Replace("\"", "QUOTE")
.Replace("VERYUNIQUEKEYWORD", "\"Settings\"")
.Replace("ANOTHERKEYWORD","\"Sname\"")
.Replace(":QUOTE",":\"")
.Replace("QUOTE,","\",");
var myObj = JsonConvert.DeserializeObject<MyResultClass>(newStr);
myObj.Settings = myObj.Settings.Replace("QUOTE", "\"");
return myObj;
}
Please note that this is NOT my recommendation.
Before saving your JSON to your DATABASE you need to serialize your JSON string.
Afterwords you can easily Deserialize your JSON.
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
};
I am using Newtonsoft.Json with version 4.0.8 and trying to use it with Web API.
So I wanted to deserialize JSON with
JsonConvert.DeserializeObject<AClass>(jsonString);
This works until I added a Dictionary as property to this class and wanted to deserialize it.
The json string is in the form of
{
"Date":null,
"AString":"message",
"Attributes":[
{"Key":"key1","Value":"value1"},
{"Key":"key2","Value":"value2"}
],
"Id":0,
"Description":"...
}
When deserializing exception of type JsonSerializationException occures with message: "Cannot deserialize JSON array into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'."
What am I doing wrong here?
UPDATE1:
When serializing with JSON.NET i get the following for the dictionary:
Attributes":{"key1":"value1","key2":"value2"}
Seems that WebApi deserializes the object in an other way than Json.Net would.
Server side I use following line for implicit deserializing:
return new HttpResponseMessage<AClass>(object);
UPDATE2:
As a workaround I came now to following line server side.
return new HttpResponseMessage<string>(JsonConvert.SerializeObject(license).Base64Encode());
I convert it with Json.Net server side and transfer it as base64 encoded string. So Json.Net can deserialize its own format.
But its still not that what I want, so are thery any further suggestions?
It should work if you declare Attributes as List<KeyValuePair<string, string>>
From this post, calling
JsonConvert.SerializeObject(yourObject, new KeyValuePairConverter());
gets your JSON in the format that the Web API is creating for you.
Ergo, one might assume that calling
JsonConvert.DeserializeObject<AClass>(jsonString, new KeyValuePairConverter());
will do the reverse and correctly handle the Web API's style.
I have no idea whether this overload even exists, though; give it a try and see what happens...
Dictionary<string, object> result = JsonConvert.DeserializeObject<Dictionary<string, object>>(strJsonResult);
If it's .NET 4, you can use DataContract attributes and the DataContractJsonSerializer Class to enforce the message format:
[DataContract]
public class Message
{
[DataMember]
public DateTime? Date { get; set; }
[DataMember]
public string AString { get; set; }
[DataMember]
public Dictionary<string, string> Attributes { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string Description { get; set; }
}
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Message));
Message message = null;
using (MemoryStream jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
// Deserialize
message = (Message)jsonSerializer.ReadObject(jsonStream);
// Go to the beginning and discard the current stream contents.
jsonStream.Seek(0, SeekOrigin.Begin);
jsonStream.SetLength(0);
// Serialize
jsonSerializer.WriteObject(jsonStream, message);
jsonString = Encoding.UTF8.GetString(jsonStream.ToArray());
}
Serializing this back out produces the following JSON:
{"AString":"message","Attributes":[{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"}],"Date":null,"Description":"...","Id":0}