var data2 = results.FormData["model2"];
Below is the sample output came from angular json data2 to convert in asp.net MVC web api
{
"0":{"RowStamp":2,"Department":"Billing and Collection"},
"1":{"RowStamp":7,"Department":"Business Development"},
"2":{"RowStamp":10,"Department":"Construction Management/Design"}
}
I have model class
public class DeptModel
{
public int RowStamp { get; set; }
public string Department { get; set; }
}
var dictionary = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<DeptModel>(data2);
Error occured during debugging
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List
Can someone help me to deserialize this to model? Much better if sample code provided. Thanks in advance
This issue resolve the problem
Model
public class DeptModel
{
public int RowStamp { get; set; }
public string Department { get; set; }
}
Deserialize to model
var data2 = results.FormData["model2"];
var dictionary = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, DeptModel>>(data2);
In usings section add
using Newtonsoft.Json.Linq;
And use following code:
var request = JArray.Parse(data2);
var dictionaryResult = keyResponse.ToObject<List<Dictionary<string, DeptModel>>>();
This way you can deserialize your JSON with Newtonsoft.Json
const string json = #"
{
""0"":{""RowStamp"":2,""Department"":""Billing and Collection""},
""1"":{""RowStamp"":7,""Department"":""Business Development""},
""2"":{""RowStamp"":10,""Department"":""Construction Management/Design""}
}";
Dictionary<string, DeptModel> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, DeptModel>>(json);
Related
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.
Is there any easy way to parse below JSOn in c#
{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [
{"status":"1","messageid":"234011120530636881","gsm":"923122699633"}
]}
and in case Multiple results.
Follow these steps:
Convert your JSON to C# using json2csharp.com;
Create a class file and put the above generated code in there;
Add the Newtonsoft.Json library to your project using the Nuget Package Manager;
Convert the JSON received from your service using this code:
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
(Feel free to rename RootObject to something more meaningful to you. The other classes should remain unchanged.)
You can safely use built-in JavaScriptSerializer without referencing additional third party libraries:
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
ser.DeserializeObject(json);
I found a way to get it without using any external API
using (var w = new WebClient())
{
var json_data = string.Empty;
string url = "YOUR URL";
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var result = jsSerializer.DeserializeObject(json_data);
Dictionary<string, object> obj2 = new Dictionary<string, object>();
obj2=(Dictionary<string,object>)(result);
string val=obj2["KEYNAME"].ToString();
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
}
For me ... the easiest way to do that is using JSON.net do a deserialize to a entity that represents the object, for example:
public class Message
{
public string status { get; set; }
public string messageid { get; set; }
public string gsm { get; set; }
}
public class YourRootEntity
{
public string type { get; set; }
public string totalprice { get; set; }
public string totalgsm { get; set; }
public string remaincredit { get; set; }
public List<Message> messages { get; set; }
}
And do this:
YourRootEntity data JsonConvert.DeserializeObject<YourRootEntity>(jsonStrong);
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;}
}
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.