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);
Related
I am calling the ServiceNow Incidents table and pulling back one incident like this. https://mydevInstance.service-now.com/api/now/v1/table/incident?sysparm_limit=1
var client = new RestClient("https://mydevInstance.service-now.com/api/now/v1/table/incident?sysparm_limit=1");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic myAuthKey");
IRestResponse response = client.Execute(request);
The JSON it returns in RESTSharp looks like this.
{
"result": [
{
"parent": "",
"made_sla": "true",
"caused_by": "",
"watch_list": "",
"upon_reject": "cancel",
"resolved_by": {
"link": "https://mydevInstance.service-now.com/api/now/v1/table/sys_user/5137153cc611227c000bbd1bd8cd2007",
"value": "5137153cc611227c000bbd1bd8cd2007"
},
"approval_history": "",
"number": "INC0000060"
}
]
}
How do I create a C# list or array of all the Keys under result? I can't Serialize the object with JSON.Net because additional keys can be added over time.
You need to grab the sample of the JSON content, then make a C# class using the 'Paste Special' option I described.
Then you can use the JsonConvert.DeserializeObject<T> (in a nuget package by Newtonsoft) to deserialize your web service response in a C# object instance.
Here are the C# classes I generated with your JSON object unaltered:
public class Rootobject
{
public Result[] result { get; set; }
}
public class Result
{
public string parent { get; set; }
public string made_sla { get; set; }
public string caused_by { get; set; }
public string watch_list { get; set; }
public string upon_reject { get; set; }
public Resolved_By resolved_by { get; set; }
public string approval_history { get; set; }
public string number { get; set; }
}
public class Resolved_By
{
public string link { get; set; }
public string value { get; set; }
}
You use this type like this:
var json = "t-b-d"; // From Web Service call
Rootobject response = JsonConvert.DeserializeObject<Rootobject>(json);
// use the response object.
** UPDATED **
If you need a more flexible model, all JSON will deserialize into Dictionary<string, string>, but I have found that serialization / deserialization results are more reliable when the model is consistent
var response = JsonConvert.DeserializeObject<Dictionary<string,string>>(json);
Here is what does work using System.Text.Json
var incidentFields = new List<string>();
var doc = JsonDocument.Parse(json);
foreach (var o in doc.RootElement.GetProperty("result").EnumerateArray())
{
foreach (var p in o.EnumerateObject())
{
incidentFields.Add(p.Name.ToString());
}
}
I created a library that handles that by default. (You can add custom types also)
https://autodati.github.io/ServiceNow.Core/
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);
I am just getting started with C# and I'm a little stuck.
How do I create a dictionary that contains a mix of string,string, string,int, and string,object?
this is what it would look like:
var values = new Dictionary<????>
{
"key0":
{
"key1": "stringValue1",
"key2": "stringValue2",
"key3": "stringValue3",
"key4": 10000
},
"key5": "stringValue4",
"key6": "stringValue5"
};
I am using this as the body for a POST request. Sample code from here
var body = new FormUrlEncodedContent(values);
var url = "http://url.com/endpoint"
var resp = await client.PostAsync(url, body);
var respString = await response.Content.ReadAsStringAsync();
This is what you said in your comment:
please note that I come from a JavaScript background where you can do whatever you want with a dictionary.
Yes you can do that in JavaScript but you need to learn and understand that C# is a strongly typed language. That does not mean you have to be strong to type it, but it means the types are known at compile time (mostly). Please read into that.
Anyhow, to do what you want to do, you can do it with a Dictionary but it will not be pretty and your fellow C# developers will not be happy with you. So how about you give your keys and values some context by creating a class (OOP). Something like below:
public class Rootobject // Give it a better name
{
public Key0 key0 { get; set; }
public string key5 { get; set; }
public string key6 { get; set; }
}
public class Key0
{
public string key1 { get; set; }
public string key2 { get; set; }
public string key3 { get; set; }
public int key4 { get; set; }
}
Now you have your class so you can create one or more instances of it:
var ro = new Rootobject();
ro.key5 = "stringValue4";
ro.key6 = "stringValue5";
var key0 = new Key0();
key0.key1 = "stringValue1";
key0.key2 = "stringValue2";
key0.key3 = "stringValue3";
key0.key4 = 1000; // See we cannot put a string here. Different than JavaScript
ro.key0 = key0;
Now you want to POST this and send it over the wire so you need to serialize it. But in your case you need to serialize it to JSON. Therefore, get NewtonSoft so it can do all the heavy lifting for you--again not saying you are not strong. Then all you need to do is this:
var json = JsonConvert.SerializeObject(ro);
Now json will be exactly like this and you can POST it to wherever:
{
"key0": {
"key1": "stringValue1",
"key2": "stringValue2",
"key3": "stringValue3",
"key4": 1000
},
"key5": "stringValue4",
"key6": "stringValue5"
}
How did I create the class?
The class above named RootObject, you can either create it manually or ask Visual Studio to do it for you. I am lazy so I asked Visual Studio to do it. If you are lazy then see my answer here.
Check this link:
HttpClient PostAsJsonAsync request
You can cast it as
var myData = await response.Content.PostAsJsonAsync<Dictionary<string, dynamic>>(...);
Then you can use it as:
string myStr = myData["key5"];
Although I would recommend you make a class with the structure and use the class name within <>
Sample class:
class MyData {
public MyData2 key0 { get; set; }
public string key5 { get; set; }
public string key6 { get; set; }
}
class MyData2 {
public string key1 { get; set; }
public string key2 { get; set; }
public string key3 { get; set; }
public int key4 { get; set; }
}
Now you can use this as:
var myData = await response.Content.PostAsJsonAsync<MyData>(...);
You can use dynamic. However, in the end, form post will convert everything into string, so you might wanna convert int and object into string first. Then, you can just use Dictionary<string, string>
Dictionary<string, dynamic> Dict = new Dictionary<string, dynamic>();
Dict.Add("string1", "1");
Dict.Add("string2", 2);
Dict.Add("string3", new object());
I have looked over example after example after example and none of my attempts have worked.
I'm attempting to deserialize this JSON return:
{
"status": "success",
"data": {
"result": "match",
"id_user": 26564,
"dob_match": null,
"first_name_match": null,
"last_name_match": null
},
"code": 200
}
Here is my JSON object class declaration:
[DataContract]
internal class DccCoachApi
{
[DataMember]
public string result { get; set; }
public string id_user { get; set; }
public string dob_match { get; set; }
public string first_name_match { get; set; }
public string last_name_match { get; set; }
}
In my stream method, my streamRead variable is filled with:
{"status":"success","data":{"result":"match","id_user":26564,"dob_match":null,"first_name_match":null,"last_name_match":null},"code":200}
Method 1 does not populate coachId:
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(streamRead)))
{
// Deserialization from JSON
var deserializer = new DataContractJsonSerializer(typeof(DccCoachApi));
var dccObj = (DccCoachApi)deserializer.ReadObject(ms);
coachId = dccObj.id_user;
}
Nor does method 2:
DccCoachApi coach = new JavaScriptSerializer().Deserialize<DccCoachApi>(streamRead);
coachId = coach.id_user;
nor does method 3:
JavaScriptSerializer js = new JavaScriptSerializer();
DccCoachApi dccObj = js.Deserialize<DccCoachApi>(streamRead);
coachId = dccObj.id_user;
nor does method 4:
dynamic dccObject = js.Deserialize<dynamic>(streamRead);
coachId = dccObject["id_user"];
The hard error that gets produced when i pull the value directly off method 4 is:
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
Methods 1-3 do not hit a hard error, however they populate coachId with no data.
Can somebody please let me know what i'm doing wrong?
You can simply generate proper classes here: http://json2csharp.com/
This is how it should look like you don't need the DataMember Attributes, it might confuse the serializer to only de-serialize this single property:
public class Data
{
public string result { get; set; }
public int id_user { get; set; }
public object dob_match { get; set; }
public object first_name_match { get; set; }
public object last_name_match { get; set; }
}
public class RootObject
{
public string status { get; set; }
public Data data { get; set; }
public int code { get; set; }
}
Code:
var deserializer = DataContractJsonSerializer(typeof(RootObject));
var root = (RootObject)deserializer.ReadObject(ms);
var coachId = root.data.id_user;
I revised the code to look like this, and it is dumping my value perfectly. Thanks much to everyone who helped me reach the solution. Plutonix, thanks as well for the paste special 411. I had no idea that existed. VERY useful!
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
var streamRead = reader.ReadToEnd();
reader.Close();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(streamRead)))
{
JavaScriptSerializer js = new JavaScriptSerializer();
DccCoachRootobject dccObj = js.Deserialize<DccCoachRootobject>(streamRead);
coachId = dccObj.data.id_user.ToString();
}
}
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.