How to Deserialize Json Object - C# - 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.

Related

Json formation for sending it to function

i want to pass following json as an reference in my console application in c#
{"val1":["dfgdsfgdfgsdf"],"val2":258915,"val3":"PPaaaA","val4":null,
"valJSON":"[{\"TypeID\":\"Z_FI_MDG\",\"SeverityCode\":\"3\",\"Note\":\"\\\"zczczca \\\\\\\"leading zero\\\\\\\". \\\\\\\\r\\\\\\\\n•YYY: Institution\"}]"}
I am doing following , but it is not working
JsonSerializer serializer = new JsonSerializer();
dynamic item = serializer.Deserialize<object>("
{"val1":["dfgdsfgdfgsdf"],"val2":258915,"val3":"PPaaaA","val4":null,
"valJSON":"[{\"TypeID\":\"Z_FI_MDG\",\"SeverityCode\":\"3\",\"Note\":\"\\\"zczczca \\\\\\\"leading zero\\\\\\\". \\\\\\\\r\\\\\\\\n•YYY: Institution\"}]"}
");
any other way i can pass this to function ?
to simplyfy
when i try to assign this to string it gives error can anyon hlp me
You should remove object type from function call:
JsonSerializer serializer = new JsonSerializer();
dynamic item = serializer.Deserialize("...");
I would use Newtonsoft's solution, if it's possible, i never regreted.
In your case, i'd use:
string json = #"{
"val1": [
"dfgdsfgdfgsdf"
],
"val2": 258915,
"val3": "PPaaaA",
"val4": null,
"valJSON": "[{\"TypeID\":\"Z_FI_MDG\",\"SeverityCode\":\"3\",\"Note\":\"\\\"zczczca \\\\\\\"leading zero\\\\\\\". \\\\\\\\r\\\\\\\\n•YYY: Institution\"}]"
}"
dynamic rss = JObject.Parse(json);
And then accessing values from it like:
var val2 = rss.val2;
I'm not sure if that's what you was looking for, but i tried...
Read more: http://www.newtonsoft.com/json/help/html/QueryJson.htm
Then, if you want more how to "install" newtonsoft: How to install JSON.NET using NuGet?
If you want to parse Json to the exact class you can try this
RootObject item = JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(#"D:\file.txt"));
public class RootObject
{
public List<string> val1 { get; set; }
public int val2 { get; set; }
public string val3 { get; set; }
public object val4 { get; set; }
public string valJSON { get; set; }
}

Cannot deserialize the current JSON object (e.g. {"name":"value"})

Please Help me out i am new in xamarin.forms and C# i have try every solution which is given in stackoverflow but cannot avail to solve
using (var httpClient = new HttpClient())
{
var response = httpClient.GetAsync(Url).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string contents = await responseContent.ReadAsStringAsync();
List<abcModel> tm = JsonConvert.DeserializeObject<List<abcModel>>(contents);
abcMaster = new ObservableCollection<SummaryModel>();
var c = tm[0].SSum.Count();
}
}
Model
public class abcModel
{
public List<SSum> SSum { get; set; }
}
public class SSum
{
public string Name{ get; set; }
}
My Json
{"a":[{"SSum":[{"Name":"Earth"}]}]}
Error:-
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[abcModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Because you obviously just want to deserialize a nested part of your json, do it like this:
var result = JsonConvert.DeserializeObject<Dictionary<string, List<abcModel>>>(json);
You're missing the a property in your JSON. You can deserialize into a class that has that property:
public class MyType
{
public List<abcModel> A { get; set; }
}
JsonConvert.DeserializeObject<MyType>(json);
Or skip that property all together (#stefankmitph's answer works well), here's another alternative:
JObject obj = JObject.Parse(json);
List<abcModel> model = obj["a"].ToObject<List<abcModel>>();
Just a note: normally C# classes are PascalCased.
If you already have the JSON string you should use a generator like json2csharp to create the response DTO. This will prevent mistakes in what is a collection versus single object.
public class SSum
{
public string Name { get; set; }
}
public class A
{
public List<SSum> SSum { get; set; }
}
public class RootObject
{
public List<A> A { get; set; }
}
Now you can deserialize the complete object:
tm = JsonConvert.DeserializeObject<RootObject>(contents);

Deserialize complex object

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.

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

Categories