How to read JSON response in c# - c#

I am using thirparty service to give me coordinates, below is the response I want to read this using c# .net in some kind of object so that I can use the information but confused how to achieve this..
{"found": 1, "bounds": [[52.45401, -1.96211], [52.45401, -1.96211]], "features": [{"id": 65140,"centroid": {"type":"POINT","coordinates":[52.45401, -1.96211]},"bounds": [[52.45401, -1.96211], [52.45401, -1.96211]],"properties": {"name": "B17 0SL"},"type": "Feature"}], "type": "FeatureCollection", "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}}
Thanks

have a look at Newtonsoft.Json its a package that will deserialize the Json into a class for you.
but you will need to create the class structure you want to use.

Use a json parser like DataContractJsonSerializer or JavaScriptSerializer
For your case for ex., using Json.Net & dynamic keyword, you can write
dynamic jObj = JsonConvert.DeserializeObject(jsonstr);
Console.WriteLine(jObj.found);
Console.WriteLine(jObj.features[0].bounds[0][0]);

You can use JsonTextReader. The following code segment may be useful, if you are not using JSON.NET
jsonString = {"found": 1, "bounds": [[52.45401, -1.96211], [52.45401, -1.96211]], "features": [{"id": 65140,"centroid": {"type":"POINT","coordinates":[52.45401, -1.96211]},"bounds": [[52.45401, -1.96211], [52.45401, -1.96211]],"properties": {"name": "B17 0SL"},"type": "Feature"}], "type": "FeatureCollection", "crs": {"type": "EPSG", "properties": {"code": 4326, "coordinate_order": [0, 1]}}};
JsonTextReader reader = new JsonTextReader(new StringReader(jsonString));
while (reader.Read())
{
if (reader.Value != null)
{
// Read Json values here
// reader.Path -> Gives you the key part.
// reader.Value.ToString() -> Gives you the value part
}
}

You can read the JSON like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
JObject joResponse = JObject.Parse(objText);
JObject result = (JObject)joResponse["result"];
array = (JArray)result["Detail"];
string statu = array[0]["dlrStat"].ToString();
}
}

You can use JSON.NET

Related

Deserializing custom dictionary

I'm getting a HttpResponse and trying to deserialize it by doing this:
response = (HttpWebResponse)request.GetResponse();
Stream objStream = response.GetResponseStream();
BinaryReader breader = new BinaryReader(objStream);
byte[] buffer = breader.ReadBytes((int)response.ContentLength);
The format is MsgPack. If I call the following code, it give me JSON like this:
var unpackKNN = MessagePack.MessagePackSerializer.ToJson(buffer);
Json
{
"__schema":{
"__level0":"result|status",
"__level1":"token|status|total|amount|details|id|name|category|cat|group",
"__level2":"method|code|timestamp|result"
},
"data":[
"__level0",
[
"__level1",
"abcd",
"true",
100,
200,
"xyz",
12345,
"Giraffe",
"1",
"One",
"First"
],
[
"__level2",
"request",
"SUCCESS",
15000000000,
"Success"
]
]
}
How should I proceed to deserialize this into a JSON array or dynamic object? Do I need to write a resolver that suits the structure of the message?
Would appreciate any help with this.
You can use the JsonConvert.DeserializeObject Method from the Newtonsoft.Json nuget .
Notice it has a couple of overloads , a non generic ones which deserialize ur json to a .Net object , and generic ones which will try to convert you json to any type u have created

JSON JObject.Parse modifies json string

I have got incomming Json in format:
{
"Type": "value",
"Name": "MeteoStation",
"UniqueAdress": "2C:3A:E8:0F:10:76",
"valuesList": [{
"Value": 23.00,
"Unit": "C",
"Type": "temperature",
"SourceUniqAdress": "2C:3A:E8:0F:10:76",
"TimeCaptured": "2018-03-26T09:36:13.200Z"
}]
}
In my program, I want to create object IValuePacket that is one value in list of values.
JObject jobject = JObject.Parse(incomingJson);
var settings = new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var incommingMessage = JsonConvert.DeserializeObject<MessageEncapsulation>(incomingJson);
string Type = incommingMessage.Type;
string name = incommingMessage.Name;
if (string.IsNullOrWhiteSpace(name))
name = "no name";
if (Type.ToLower().Equals("value")) {
var values = JsonConvert.DeserializeObject<List<IValuePacket>>(jobject["valuesList"].ToString());
}
Everything works fine untill I recieved exact this json as mention above.
JObject.Parse modifies value TimeCaptured and jobject looks like:
{
"Type": "value",
"Name": "Meteostation",
"UniqueAdress": "2C:3A:E8:0F:10:76",
"valuesList": [{
"Value": 23.00,
"Unit": "C",
"Type": "temperature",
"SourceUniqAdress": "2C:3A:E8:0F:10:76",
"TimeCaptured": "2018-03-26T09:36:13.2Z"
}]}
Thats not so much difference, but DateTime.ParseExact(value, "yyyy-MM-ddThh:mm:ss.fffZ", System.Globalization.CultureInfo.InvariantCulture); cannot parse new value. Actually, I am sending 201 ms instead of 200 ms. It works, but I want to have good time for future reasons.
Is there any way how to avoid changing in Json during parsing?
It does not really modify your string, it just parses your date string into DateTime object when you call JObject.Parse. If you do this:
var obj = JObject.Parse(json);
var values = (JArray) obj["valuesList"];
var time = (JValue) values[0]["TimeCaptured"];
Console.WriteLine(time.Value.GetType());
You notice that time.Value is of type DateTime. Then you do this:
JsonConvert.DeserializeObject<List<IValuePacket>>(jobject["valuesList"].ToString());
By doing that you convert valueList back to json, but now TimeCaptured is DateTime and not a string, so that DateTime object is converted to json string using whatever date time format is used by JSON.NET by default.
You can avoid parsing strings that look like dates to .NET DateTime objects by parsing json to JObject like this:
JObject obj;
using (var reader = new JsonTextReader(new StringReader(json))) {
// DateParseHandling.None is what you need
reader.DateParseHandling = DateParseHandling.None;
obj = JObject.Load(reader);
}
Then type of TimeCaptured will be string, as you expect.
Side note: there is no need to convert JToken back to string and then call JsonConvert.Deserialize on that string. Instead, do this:
var values = obj["valuesList"].ToObject<List<IValuePacket>>();

How to get JSON values into a string array?

I am using VS2010 with C# 4. I have JSON similar to the following:
{"ItemDetails":{"Item":{"val": [
{"Description":"Desk1","Amount":"100.00"},
{"Description":"Desk2","Amount":"200.00"},
{"Description":"Desk3","Amount":"300.00"}]}}}
I want to get all the amount values into one string array like what is shown below:
amount={100.00,200.00,300.00}
How could I implement this? Do I have to loop through the JSON object or is there another way to do this?
I would recommend using NewtonSofts JSON library, but another (yet ugly) way is to use Regular Expressions.
var json = "{\"ItemDetails\":{\"Item\":{\"val\": [ " +
"{\"Description\":\"Desk1\",\"Amount\":\"100.00\",}," +
"{\"Description\":\"Desk2\",\"Amount\":\"200.00\",}," +
"{\"Description\":\"Desk3\",\"Amount\":\"300.00\"}}}";
// What I think you want
var amount = Regex.Matches(json, "Amount\":\"(.*?)\"").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
// Values 'converted' to json
var jsonAmount = "amount={" + string.Join(",", amount) + "}";
Using Json.Net you can do this with a LINQ-to-JSON query:
string json = #"
{
""ItemDetails"": {
""Item"": {
""val"": [
{
""Description"": ""Desk1"",
""Amount"": ""100.00""
},
{
""Description"": ""Desk2"",
""Amount"": ""200.00""
},
{
""Description"": ""Desk3"",
""Amount"": ""300.00""
}
]
}
}
}";
JToken token = JToken.Parse(json);
string[] amounts = token.SelectToken("ItemDetails.Item.val")
.Children()
.Select(t => t["Amount"].ToString())
.ToArray();
Console.WriteLine("amount={" + string.Join(",", amounts) + "}");
Output:
amount={100.00,200.00,300.00}
I am assuming you are not using JSON.NET. If this the case, then you can try it.
It has the following features -
LINQ to JSON
The JsonSerializer for quickly converting your .NET objects to JSON and back again
Json.NET can optionally produce well formatted, indented JSON for debugging or display
Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
Ability to convert JSON to and from XML
Supports multiple platforms: .NET, Silverlight and the Compact Framework
Look at the example below.
In this example, JsonConvert object is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject(String json) -
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject(json);

Passing Array from Javascript to C#

I have a .js script that contain an array:
The output of the js is like:
var foo=
[
{
"bar1":"value1",
"bar2":"value2"
// And so on...
}
]
I have no access to the js source, so i cannot output as JSON and Deserialize.
I can only get this as a String using WebClient, but how i can parse it and create an Array/Dictionary and work on it inside C#?
You should consider calling WebClient.DownloadString . Then Parse using JSON.Net or whatever
As per the example provided over there
string json = #"{
""Name"": ""Apple"",
""Expiry"": "2008-12-28T00:00:00",
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
var foo = new JavaScriptSerializer().Deserialize<List<YourModelHere>>(YourString);
You can use a JavaScriptSerializer to deserialize that string:
string str=
#"var foo =
[
{
""bar1"":""value1"",
""bar2"":""value2""
}
]";
JavaScriptSerializer js = new JavaScriptSerializer();
var o = js.Deserialize<Dictionary<string,string>[]>(str.Substring(str.IndexOf('[')));
Result:
Dictionary<String,String> (2 items)
Key Value
------ --------
bar1 value1
bar2 value2

JSON trouble; deserialising to a datatable

I am trying to load JSON into a SQL database using JSON.net.
I've had no issues with other JSON responses however the following format doesn't seem to deserialise correctly.
{"Report":["2012m01d01","2012m01d02","2012w01","2012m01","2012m01d03","2012m01d04","2012m01d05","2012m01d06","2012m01d07","2012m01d08"],
"Realtime":null}
Could anybody provide some insight into why this would be? I'm using the following code to deserialise with.
public void Deserialize(String jsonText, ref DataTable dt)
{
JsonSerializer json = new JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = ObjectCreationHandling.Replace;
json.MissingMemberHandling = MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
StringReader sr = new StringReader(jsonText);
JsonTextReader reader = new JsonTextReader(sr);
dt = (DataTable)json.Deserialize(reader, typeof(DataTable));
reader.Close();
}
Any ideas on what the best approach to solving this would be? This works fine with other JSON responses!
Thanks in advance
JSON is able to hold hirarchial information, that does not translate into a single datatable, but rather into several using a dataset and table relationships.
I put your json in http://jsonlint.com validator and formatter
you say this deserializes with no problems
{
"accountID": 1,
"profileID": null,
"name": "Pages",
"ID": "18d039ae0360",
"language": n‌​ull,
"type": null,
"Category": null,
"IsHierarchy": false,
"IntervalsEnabled": true,
"IsRe‌​altimeCompatible": true,
"properties": null
}
this is a single object
but this doesn't deserialize properly.
{
"Report": [
"2012m01d01",
"2012m01d02",
"2012w01",
"2012m01",
"2012m01d03",
"2012m01d04",
"2012m01d05",
"2012m01d06",
"2012m01d07",
"2012m01d08"
],
"Realtime": null
}
Actually your problem is data handling not serializion
the first is a single object and can be deserialized into a DataTable
and the other is an object that holds a reference to a list of report objects.
therefore you need to manually write a converter from your object to two dataTables
this code works, and i'm sure you can create a conversion function for your two tables
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Error,
NullValueHandling = NullValueHandling.Include
};
JsonSerializer json = JsonSerializer.Create(settings);
json.Error += (x, y) =>
{
var s = y.ErrorContext;
var t = y.CurrentObject;
};
StringReader sr = new StringReader(jsonString);
JsonTextReader reader = new JsonTextReader(sr);
var o = json.Deserialize<ClsReport>(reader);
string sf = o.ReportItems[2];
Hope this helps

Categories

Resources