Deserializing custom dictionary - c#

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

Related

C# JSON Deserialise / Get Data Pair from Data Name at Runtime

I want to create a method with the C# Newtonsoft library that can take in a parameter value to return the JSON data value, without needing to know and create a class beforehand, but all I can find are examples to deserialise into a class or into a dynamic object, both needing to know JSON structure prior at development time
Here's an example of what the kind of JSON format I'm expecting, but is subject to change:
{
"Input":
[
{
"Name": "foo"
},
{
"Name": "bar"
},
]
"Output":
[
{
"Name": "bob"
},
{
"Name": "builder"
},
]
}
I'm locked into using Newtonsoft library to work on the JSON file, or do it myself from scratch as it's an embedded system.
You can use JObject. If you deserialize a class without the type it will be deserialized to JObject. You would access your JObject values with named index which is obviously your property name. Other type of interest to you is JArray. This all resides in namespaces:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Example:
So the example with your JSON would be:
var json = #"{
""Input"":
[
{ ""Name"": ""foo"" },
{ ""Name"": ""bar"" }
],
""Output"":
[
{ ""Name"": ""bob"" },
{""Name"": ""builder""}
]
}";
var obj = JsonConvert.DeserializeObject(json) as JObject;
var input = obj["Input"] as JArray;
var inputArray = input[0]["Name"];
This would get the first element in array that is in Input field - "foo".

.NET MongoDB: Deserialize BsonDocument from BsonType Array

I look for the answer but nothing helps, so I post the question again, hope someone could help me out.
Let's say I have a simple JSON string like this:
[
{
"id": 1,
"name": "A"
},
{
"id": 2,
"name": "B"
}
]
And here is my code to parse that JSON into BsonDocument
using (var jsonreader = new JsonReader(json_data))
{
var context = BsonDeserializationContext.CreateRoot(jsonreader);
//Bson Array, how to deserialize???
var document = collection.DocumentSerializer.Deserialize(context);
collection.InsertOne(document);
}
It will return the error "System.FormatException: 'Cannot deserialize a 'BsonDocument' from BsonType 'Array'.'
If you want to directly convert Json to BsonDocument you should do it as following:
BsonDocument document = BsonDocument.Parse(json_data.toString());
You might want to share more of your code to give clearer picture of what are you trying to do. Anyway, I hope this sorts your issue.

Can I LINQ a JSON?

This is the JSON I get from a request on .NET:
{
"id": "110355660738",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/1027085_12033235063_5234302342947_n.jpg",
"is_silhouette": false
}
}
}
and I'd like to catch the field "url", using (maybe?) LINQ. I do many request as this, that differents a bit. So I won't to create a C# Class and deserialize it every time.
Is it a way to extract a single field? Thank you!
No need for Linq, just use dynamic (using Json.Net)
dynamic obj = JObject.Parse(json);
Console.WriteLine((string)obj.picture.data.url);
Linq version would not be much readable
JObject jObj = JObject.Parse(json);
var url = (string)jObj.Descendants()
.OfType<JProperty>()
.Where(p => p.Name == "url")
.First()
.Value;
Documentation: LINQ to JSON
I would not recommend LINQ. I would recommend a JSON library such as newtonsoft.json.
So you can do this:
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
Note:- this code has been copied from the samples present on the project site
http://james.newtonking.com/pages/json-net.aspx
In a bind you could always deserialize the JSON and serialize it to XML, and load the XML in a XDocument. Then you can use the classic Linq to XML. When you are done take the XML, deserialize it, and serialize it back to JSON to JSON. We used this technique to add JSON support to an application that was originally built for XML, it allowed near-zero modifications to get up and running.
You can easily query with LINQ like this
considering this JSON
{
"items": [
{
"id": "10",
"name": "one"
},
{
"id": "12",
"name": "two"
}
]
}
let's put it in a variable called json like this,
JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
you can select all ids from the items where name is "one" using the following LINQ query
var Ids =
from item in json["items"]
where (string)item["name"] == "one"
select item["id"];
Then, you will have the result in an IEnumerable list

Deserialize json with Json.NET

I have JSON that looks like this (from the Philips HUE API):
{
"1": {"name": "Bedroom"},
"2": {"name": "Kitchen"}
}
When I try to deserialize this document I run into problems because the document is structured the way it is.
If it had been formated like this:
[
{"nr": "1", "name": "Bedroom"},
{"nr": "2", "name": "Kitchen"}
]
Everything would have been fine. Now I am forced to do string parsing in order to extract the data... :-(
Any ideas or suggestions?
I would deserialize to JObject and use it as Dictionary
var jObj = (JObject)JsonConvert.DeserializeObject(json);
Console.WriteLine(jObj["1"]["name"]);
or
dynamic jObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jObj["1"].name);

How to read JSON response in 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

Categories

Resources