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;}
}
Related
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.
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.
I have a JSON string like:
var json = "{\"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}";
I want to design a class for the same; how does one approach while creating a class for JSON string in C# ?
If you are using Visual Studio 2012, go in the menu to EDIT -> Paste Special -> Paste JSON As CLasses.
You valid JSON should probably look like this (you should remove the \ before copying it to the clipboard):
{"Attributes": {"name":"S1", "quantity":"100"}}
The generated classes:
public class Rootobject
{
public Attributes Attributes { get; set; }
}
public class Attributes
{
public string name { get; set; }
public string quantity { get; set; }
}
Sample usage (note that the \ is still here, in order to have valid code syntax):
var json = "{\"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}";
var json_serializer = new JavaScriptSerializer();
Rootobject dc = json_serializer.Deserialize<Rootobject>(json);
You're question's unclear, but I assume you mean parsing JSON in to C# objects? Using JSON.NET and something like this can do that:
public class Attributes
{
[JsonProperty("name")]
public String Name { get; set; }
[JsonProperty("quantity")]
public Int32 Quantity { get; set; }
}
public class MyObject
{
[JsonProperty("Attributes")]
public Attributes Attributes { get; set; }
}
var myObj = JsonConvert.DeserializeObject<MyObject>(json);
Or you can go more broadly and let JSON.NET do it for you:
var obj = JsonConvert.DeserializeObject<dynamic>(
"{ \"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}"
);
Console.WriteLine(obj.Attributes["name"]) // S1
Console.WriteLine(obj.Attributes["quantity"]) // 100
have a look at the namespace System.Runtime.Serialization, you can find useful classes for (de)serializing JSON there
also you can read this similar question (searching before posting does not really hurt):
How do I represent this complex json document as a C# object?
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"));
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.