Deserialize complex object - c#

I'm trying to deserialize an object sent by the browser. My object is array of Detail with the name as key. The name is a string and the detail an object with properties.
this is Picture of the javascript object:
And this is the JSON String I receive, created with "JSON.stringify(TemplateDetails)":
"{\"UDF1-0-div\":{\"UDFtitle\":\"theTitle\",\"DDLType\":\"STRING\",\"defaultValue\":\"defVal\",\"minLength\":\"1\",\"maxLength\":\"6\",\"decimals\":\"\",\"DDLTable\":\"\",\"DDLFilter\":\"\",\"DDLAction\":\"TEST\",\"DDLfontfamily\":\"Verdana\",\"DDLSize\":\"12px\",\"DDLTextAlignment\":\"left\",\"colorTitle\":\"#FFFFFF\",\"colorText\":\"#FFFFFF\"}}"
I want to recreate the object in the c# code.

First of all you should create a class with all of properties you need :
public class MyClass
{
public string DDLAction{ get; set; }
public string DDLFilter{ get; set; }
public string DDLSize{ get; set; }
// put all of your attributes
//...
}
And for deserialization :
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
MyClass Obj = ser.Deserialize<MyClass>(input);

That's not a dictionary, a dictionary looks like this:
{
"objName": {
["title", "thetitle"],
["DDLType":"STRING"],
["defaultValue": "defVal"]
}
}
You got a regular object and will have to create it as such.

Related

How to Deserialize Json Object - C#

A web service returns JSON object as blew:
JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}"
I tried to Deserialize by doing this:
Define the objects
public class RootResponseClass
{
public ResponseParametersClass[] d { get; set; }
}
public class ResponseParametersClass
{
public string sname { get; set; }
public string region { get; set; }
public string name { get; set; }
}
Write the Deserialize Method
JavaScriptSerializer ser2 = new JavaScriptSerializer();
RootResponseClass obj = new RootResponseClass();
obj = ser2.Deserialize<RootResponseClass>(JsonString);
But It is gives error "Cannot convert object of type 'System.String' to type 'NAS.Helpers.ResponseParametersClass[]", So how can i do it!
Solution
public class RootResponseClass
{
public string d { get; set; }
}
And for deserialize method :
JavaScriptSerializer ser2 = new JavaScriptSerializer();
RootResponseClass obj = new RootResponseClass();
obj = ser2.Deserialize<RootResponseClass>(JsonString);
List<ResponseParametersClass> obj2 = new List<ResponseParametersClass>();
obj2 = ser2.Deserialize<List<ResponseParametersClass>>(obj.d.ToString());
You can use the package using Newtonsoft.Json; for deserializing JSON
example
JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}";
var foo = JsonConvert.DeserializeObject<RootResponseClass>(JsonString);
foo is your deserialized object.
EDIT
As extra information why the initial way is not working is because your array is starting with quotes so its recognized as a string. After the "{"d": should be just [] instead of "[]"
Thanx Dnomyar96 for pointing that extra out.
Your Json string seems to contain another Json string. So in order to deserialize this, you'd need to deserialize as you're doing now, but change the ResponseParametersClass to string.
Then you'd need to deserialize the string you just got (as a List<ResponseParametersClass>). So in this case you'd need to deserialize in two seperate steps.

Deserialization of JSON in c#

I have the following JSON
{
"employee" : {
"property1" : "value1",
"property2" : "value2",
//...
}
}
to a class like
public class employee
{
public string property1{get;set;}
public string property2{get;set;}
//...
}
In my JSON if I need to add property3 then I need to make changes in my class too.
How can I deserialize to a class even though if I change my JSON(adding another property like property3).
The serialize/De-serialize techniques like newtonsoft.json is tightly coupled with the Class.
Is there a better way/tool to deserialize these kind of JSON in portable class in c#?
Newtonsoft is not tightly coupled with strong types. You can deserialize the dynamic types too. See the similar question here (How to read the Json data without knowing the Key value)
You can try .net's JavaScriptSerializer (System.Web.Script.Serialization.JavaScriptSerializer). If some field is added or removed it deserializes object normally.
namespace ConsoleApplication8
{
public class Person
{
public int PersonID { get; set; }
//public string Name { get; set; }
public bool Registered { get; set; }
public string s1 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var s = "{\"PersonID\":1,\"Name\":\"Name1\",\"Registered\":true}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = serializer.Deserialize<Person>(s);
;
}
}
}
If we can use " Dictionary<string,string> employee" the above json can be deserilized.

Unable to deseralize JSON

Im trying simply to deserialize a JSON payload using the JavaScriptSerializer class and running into an issue of the class property im setting this supposed deserialized data too being 'null'.
JSON:
{
"XmlPayload": "<PaperLessTimeSheetActivation xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://host.adp.com\"><iSIClientID>99783971</iSIClientID><organizationId>FDGFGD</organizationId><statusDescription>Success</statusDescription></PaperLessTimeSheetActivation>"
}
Here my code:
var jsObject = new JavaScriptSerializer();
string holdData = xmlPayload.ToString();
//*****issue: JSON XmlPayLoadConvert property is 'null'.
JSONConverted objectToConvert = jsObject.Deserialize<JSONConverted>(holdData);
string stringXDoc = ConvertToXDoc(objectToConvert.XmlPayloadToConvert);
Here the class the deserialized data should map too:
public class JSONConverted
{
public string XmlPayloadToConvert
{
get;
set;
}
}
Can anyone tell me where I'm going wrong?
With the edit the error becomes obvious: XmlPayload is not the same as XmlPayloadToConvert.
Change your type to:
public class JSONConverted
{
public string XmlPayload {get;set;}
}
and it'll work fine. With some serializers (Json.NET, for example) you can also tell it how to map the names:
[DataContract]
public class JSONConverted
{
[DataMember(Name = "XmlPayload") ]
public string XmlPayloadToConvert {get;set;}
}

deserialize json into .net object using json.net

I am having a problem deserializing some JSON string back into .net objects. I have a container class which contains some information from external and there is a field call ClassType which defined what type of information is that and the actual content is in another property, which currently can be anything, so we define that as an Object type.
Following are the .net class definition which helps to understand the issue.
class ClassOne
{
public string Name { get; set; }
public int Age { get; set; }
}
class ClassTwo
{
public string AddressLine { get; set; }
public string AddressLine2 { get; set; }
}
class ClassThree
{
public string Country { get; set; }
public string Passport { get; set; }
}
class ContainerClass
{
public string ClassType { get; set; }
public object ClassContent { get; set; }
}
When getting the information from external in a JSON format it will be something like:
{"ClassType":"Class1","ClassContent":{"Name":"James","Age":2}}
I am using Newtonsoft JSON.net library to deserialize the JSON string. It seems like that the default deserialize function will just deserialize that into an Newtonsoft.Json.Linq.JContainer. I just wondering how can I write some Converter to deserialize the ClassContent based on the ClassType definition. Any code sample will be highly appreciated.
I would go dynamic way, like:
string json = #"{""ClassType"":""Class1"",""ClassContent"":{""Name"":""James"",""Age"":2}}";
dynamic jObj = JObject.Parse(json);
if (jObj.ClassType == "Class1")
{
Console.WriteLine("{0} {1}", jObj.ClassContent.Name, jObj.ClassContent.Age);
}
Since returning an object (ClassContent) doesn't mean much, and you have to cast it to a concrete class somehow (using some if's or switch).
Sample:
var container = JsonConvert.DeserializeObject<ContainerClass>(json);
JContainer content = (JContainer)container.ClassContent;
switch(container.ClassType)
{
case "Class1": return container.ToObject(typeof(ClassOne));
..
}
use dynamic and call .ToObject(Type type)
dynamic root = JObject.Parse(json)
return root["ClassContent"].ToObject(Type.GetType(root["ClassType"]))
Try the following
var jsonObject = JObject.Parse(jsonString);
var result = jsonObject.ToObject(Type.GetType("namespace.className"));

Parsing JSON data in C#

I have a JSON data as follows
{"id": "367501354973","from": {
"name": "Bret Taylor",
"id": "220439" }
which is returned by an object(result) of IDictionary[String, Object]
In my C# code:
I have made a class for storing the JSON value which is as follows
public class SContent
{
public string id { get; set; }
public string from_name { get; set; }
public string from_id { get; set; }
}
My main C# function which stores the parses the JSON data and stores the value inside the class properties is as follows:
List<object> data = (List<object>)result["data"];
foreach (IDictionary<string, object> content in data)
{
SContent s = new SContent();
s.id = (string)content["id"];
s.from_name = (string)content["from.name"];
s.from_id = (string)content["from.id"];
}
When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"
When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.
I think i am not able to refer the nested JSON data properly.
Can anyone just validate it and please tell me how to refer nested data in JSON in C#?
Thanks
I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?
You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)
Using that class, you would write your code like this:
public class SContent
{
public string id { get; set; }
public SFrom from { get; set; }
}
public class SFrom
{
public string name { get; set; }
public string id { get; set; }
}
Then deserialization looks like this:
var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);
See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

Categories