I am looking for a JSON library which is able to do the following:
PC 1
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
PC 2
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
As you can see, there was no need to create a class in order to send the name and age value pairs. Now, this code is in Java. Is there a library in .NET which does this? I checked the documentation for JSON.NET, however it appears that it does not offer the use of a JSONobject where we can add value pairs.
You can use Json.Net
dynamic jsonObject = new JObject();
jsonObject.Name = "mkyong.com";
jsonObject.Age = 100;
var json = jsonObject.ToString();
output:
{
"Name": "mkyong.com",
"Age": 100
}
or without dynamic
JObject jsonObject = new JObject();
jsonObject["Name"] = "mkyong.com";
jsonObject["Age"] = 100;
var json = jsonObject.ToString();
You can even make use of anonymous classes
var json = JsonConvert.SerializeObject(new {Name="mkyong.com", Age=100 });
Related
I am trying to return a JSON result from a REST API that includes a JsonObject as an element.
var aJsonObject = new JObject();
aJsonObject.Add("somefield", "somevalue" );
aJsonObject.Add("someotherfield", 1995);
return Json( new { status = "success", result = aJsonObject } );
The client receives an empty nested arrays:
{"status":"success","result":[[[]],[[]]]}
My work around, which I don't love, is to serialize the JsonObject, thus sending it as a string and then having the client parse it. It works, but it's a bit ugly.
Is this a bug or am I doing it wrong?
NOTE: 8/3/18 I edited the variable declaration to correct a typo - it was jsonObject and should have been aJsonObject
JObject is already json-formatted. Main purpose of JsonResult is to serialize an object to json. What you are trying to do is (I guess):
dynamic resultObject = new ExpandoObject();
resultObject.somefield = "somevalue";
resultObject.someotherfield = 1995;
return Json( new { status = "success", result = resultObject } );
If you want to build the Json string yourself and return it to the client you can use Content:
return new Content(yourjsonstring, "application/json");
And if you want to keep using JObject, this works (and then return the JSON as #ozum.e describes):
var jObject = new JObject();
jObject.Add("someField", "someValue");
jObject.Add("otherField", 1995);
var newObj = new { status = "success", result = jObject };
var returnThis = JsonConvert.SerializeObject(newObj);
From the result of an API call I have a large amount of JSON to process.
I currently have this
Object convertObj = JsonConvert.DeserializeObject(responseFromServer);
I am aware that I could do something like
Movie m = JsonConvert.DeserializeObject<Movie>(responseFromServer);
And then use it like
m.FieldName
m.AnotherField
//etc
Ideally I would like to do something like
var itemName = convertObj["Name"];
to get the first Name value for the first item in the list.
Is this possible, or do I have to create a class to deserialize to?
The reason I do not want to create the class is I am not the owner of the API and the field structure may change.
Edit.
Okay so I created the class as it seems the best approach, but is there a way to deserialize the JSON into a list?
var sessionScans = new List<SessionScan>();
sessionScans = JsonConvert.DeserializeObject<SessionScan>(responseFromServer);
Complains that it cannot convert SessionScan to generic list.
No need to use dynamic, you can simply use JToken which is already does what you expect:
var json = #"
{
""someObj"": 5
}
";
var result = JsonConvert.DeserializeObject<JToken>(json);
var t = result["someObj"]; //contains 5
With .NET 6, this can be done as below,
using System.Text.Json;
using System.Text.Json.Nodes;
string jsonString = #"some json string here";
JsonNode forecastNode = JsonNode.Parse(jsonString)!;
int temperatureInt = (int)forecastNode!["Temperature"]!;
Console.WriteLine($"Value={temperatureInt}");
//for nested elements, you can access as below
int someVal = someNode!["someParent"]["childId"]!.ToString();
Refer this MS docs page for more samples - create object using initializers, make changes to DOM, deserialize subsection of a JSON payload.
You can try with JObject.Parse :
dynamic convertObj = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = convertObj.Name;
string address = convertObj.Address.City;
The below example can deserialize JSON to a list of anonymous objects using NewtonSoft.Json's DeserializeAnonymousType method.
var json = System.IO.File.ReadAllText(#"C:\TestJSONFiles\yourJSONFile.json");
var fooDefinition = new { FieldName = "", AnotherField = 0 }; // type with fields of string, int
var fooListDefinition = new []{ fooDefinition }.ToList();
var foos = JsonConvert.DeserializeAnonymousType(json, fooListDefinition);
You can use Json.NET's LINQ to JSON API
JObject o = JObject.Parse(jsonString);
string prop = (string)o["prop"];
Use Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var json = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]";
var ja = (JArray)JsonConvert.DeserializeObject(json);
var jo = (JObject) ja[0];
Console.WriteLine(jo["a"]);
I had this problem working with unknown APIs then I decide to come over this problem using this approach, I'm writing down here my test case:
[TestMethod]
public void JsonDocumentDeserialize()
{
string jsonResult = #"{
""status"": ""INTERNAL_SERVER_ERROR"",
""timestamp"": ""09-09-2019 11:00:24"",
""message"": ""documentUri is required.""
}";
var jDoc = JsonDocument.Parse(jsonResult);
if (jDoc.RootElement.TryGetProperty("message", out JsonElement message))
{
Assert.IsTrue(message.GetString() == "documentUri is required.");
}
}
it worked for me because first I was looking to find a way to use dynamic type as it's mentioned in Azure Function HTTPTrigger. But I found this approach most useful and robust.
Microsoft Reference
My question is simple but i can not do that. i wanna get value of "soap:Body" from below string by C#code?
{"soap:Envelope":{"xmlns:xsd":"http://www.w3.org/2001/XMLSchema","xmlns:soap":"http://www.w3.org/2003/05/soap-envelope","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","soap:Body":{"ToplamaResponse":{"xmlns":"http://tempuri.org/","ToplamaResult":156758}}}}
You can also use the Framework class JavaScriptSerializer if you do not want to use an external library.
string json = #"...";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var o = serializer.Deserialize<dynamic>(json);
var body = o["soap:Envelope"]["soap:Body"];
You can do it easily by using Json.NET
dynamic data = JObject.Parse("{'soap:Envelope':{'xmlns:xsd':'http://www.w3.org/2001/XMLSchema','xmlns:soap':'http://www.w3.org/2003/05/soap-envelope','xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','soap:Body':{'ToplamaResponse':{'xmlns':'http://tempuri.org/','ToplamaResult':156758}}}}");
string soap_body = data["soap:Envelope"]["soap:Body"];
There is a simple example in the JObject.Parse documentation
string json = #"{
"soap:Envelope": {
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"soap:Body": {
"ToplamaResponse": {
"xmlns": "http://tempuri.org/",
"ToplamaResult": 156758
}
}
}
}";
JObject obj = JObject.Parse(json);
Console.WriteLine((string)obj["soap:Envelope"]["soap:Body"]);
And if you want to manipulate the value of "soap:Body" do the same thing :)
How to deserialize with keyvaluepair the above json
string stations = [{"2":false,"1":"Aforre","0":"WS6"},{"2":false,"1":"Alodtau","0":"WS3"},{"2":false,"1":"Balimo Station","0":"WS36"}]
I what like this
var get = js.Deserialize<Dictionary<string,dynamic>>(stations);
try this:
string stations = "[{'2':false,'1':'Aforre','0':'WS6'},{'2':false,'1':'Alodtau','0':'WS3'},{'2':false,'1':'Balimo Station','0':'WS36'}]";
var serializer = new JavaScriptSerializer();
dynamic value = serializer.DeserializeObject(stations);
and you can access objects like:
var a = value[0]["0"];
and a will have "WS6" (according to your JSON)
The JSON shown is an array. You might try desetializing to:
Dictionary<string, object>[]
i.e.
var get = js.Deserialize<Dictionary<string,object>[]>(stations);
One of the best option is create a class that consist of all keyvalue pair and then deserialize json string to the object of created class
You can try using dynamic variable as following:
string stations = "[{'2':false,'1':'Aforre','0':'WS6'},{'2':false,'1':'Alodtau','0':'WS3'},{'2':false,'1':'Balimo Station','0':'WS36'}]";
var serializer = new JavaScriptSerializer();
dynamic serializevalues = serializer.DeserializeObject(stations);
var valueof1 = serializevalues[0]["1"];
Response.Write(valueof1);
The above will print output "Aforre'.
I need to get currency values list in C# from here:
http://openexchangerates.org/currencies.json
which produces this kind of output:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder",
"AOA": "Angolan Kwanza"
// and so on
}
I managed to get a string containing values above using C#, but I cannot find a way to deserialize that string into any custom class or anonymous object, so I am wondering how to do that?
Also, I am trying to use Json.NET to do that, but so far couldn't find a solution...
using Json.Net
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
--EDIT--
You can make it shorter
WebClient w = new WebClient();
string url = "http://openexchangerates.org/currencies.json";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(w.DownloadString(url));
A solution using only .Net 4.0 and no third party libraries:
string url = "http://openexchangerates.org/currencies.json";
var client = new System.Net.WebClient();
string curStr = client.DownloadString(url);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = (js.DeserializeObject(curStr) as Dictionary<string, object>)
.Select(x => new { CurKey = x.Key, Currency = x.Value.ToString() });
Outputs a list of anonymous objects with the keys and values from the list as properties.
Enjoy :)