Json Deserialize a webclient response C# - c#

I am new in C# and I know there are hundreds of examples on the google for Json deserialization. I tried many but could not understand how C# works for deserialization.
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "text/json");
result = client.UploadString(url, "POST", json);
}
result looks like this:
{"Products":[{"ProductId":259959,"StockCount":83},{"ProductId":420124,"StockCount":158}]}
First I created a class:
public class ProductDetails
{
public string ProductId { get; set; }
public string StockCount { get; set; }
}
Then I tried to deserialize using this statement but couldn't understand.
var jsonresult = JsonConvert.DeserializeObject<ProductDetails>(result);
Debug.WriteLine(jsonresult.ProductId);
The above worked fine in visual basic with the following code but how to do this similar in C#
Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlHttp.responseText)
For Each Product In Json("Products")
Debug.Print = Product("ProductId")
Debug.Print = Product("StockCount")
Next Product

You should use:
public class Product
{
public int ProductId { get; set; }
public int StockCount { get; set; }
}
public class RootObject
{
public List<Product> Products { get; set; }
}
var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);
Because your JSON contains list of products, in jsonresult you have list of Product.
If you want get Product you can use eg. foreach
foreach(Product p in jsonresult.Products)
{
int id = p.ProductId;
}

Your JSON reads "an object that has a property named Products which contains an array of objects with properties ProductId and StockCount". Hence,
public class Inventory
{
public ProductDetails[] Products { get; set; }
}
var inventory = JsonConvert.DeserializeObject<Inventory>(result);

Your C# code cannot work because your json string contains values for 2 Product objects. As a result your var jsonresult variable will contain an array of Product objects, not one.
It is obvious in your VB code as you need to loop the Json variable in order to acquire each Product object.
Still your C# code would work if you string contained values for only one object like this:
{"ProductId" = 420124,"StockCount" = 158}
as you can see here http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Also you can try json parsing with JObject class, check this out: http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jobject.htm

Related

Looping through a Json array (C#)

I have been working on some automated tests with selenium and I need to get some data out of a JSON file.
how can i go about coding this, i have this so far
string json = File.ReadAllText("myfilepath");
dynamic data = jsonConvert.DeserializeObject(json);
string x = data[0].CountryName.Value;
foreach(var CN in data.countryName)
{
var CountryName = CN.CountryName;
}
I am a bit stuck on getting data through to loop it
Any help would be amazing guys
Example Json :
[
{
"CountryLookupId":123,
"CountryName":data,
"CountryLocation": moredata
}
]
I am trying to loop through the CountryName,i need to loop through 31 things
With out testing it. make a object model:
public class CountryClass
{
[JsonProperty("CountryLookupId")]
[JsonConverter(typeof(ParseStringConverter))]
public long CountryLookupId { get; set; }
[JsonProperty("CountryName")]
public string CountryName { get; set; }
[JsonProperty("CountryLocation")]
public string CountryLocation { get; set; }
}
Than deserialize list of object model:
List<CountryClass> data = jsonConvert.DeserializeObject<List<CountryClass>>(json);
Finally you can loop over your list of country objects:
foreach(var cn in data)
{
var countryName = cn.CountryName;
}

how to serialize nested list into json format

I have a List Object which internal contains a list of Products Object. I have to return this as a Json format to UI.
Here is the sample nested List which I am getting.
How to add List<B> to Object A, where List<B> is part of class A
I am using JsonResult to return a Json format, but only Customer list Object is getting converted. inner list Product object is missing.
Please someone suggest me how the nested list gets serialized.
Say you have two list
public class Customer
{
[JsonProperty("customer_id")]
public int CustomerId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("products")]
public List<Products> Products { get; set; }
}
public class Products
{
[JsonProperty("product_id")]
public string ProductId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
//initialize Object of Customer here
Use Newtonsoft to convert Customer object into json
var jsonString = JsonConvert.SerializeObject(objCustomer);
You can also take advantage of several formatting options available.
Update
Per your comment - pass the serialize data
return Ok(JsonConvert.SerializeObject(objCustomer))
Also, if you direct pass objCustomer like
return Ok(objCustomer)
it should return you Json (provided you have not configured your project to return another format by default)
assuming you want to return the customers list from your previous post:
you need to import Newtonsoft.Json package into your application
using Newtonsoft.Json;
public your_method() {
List<Customer> customers = your_method_to_return_curstomers();
var jsonValue = Newtonsoft.Json.JsonConvert.SerializeObject(customers);
}
Fiddle example
please init your Products list in Customer constructor (I don't now if this can be a possibility for your problem)
public class Customer
{
public Customer() {
Products = new List<Product>();
}
public int CustomerId {get;set;}
public string Name {get;set;}
public List<Products> Products {get;set;}
}

Unable to map JSON response to a predefined class in C# / dynamic property name

I have a class which basically contains a property like this:
public class Msg
{
[JsonProperty(PropertyName = "XD1703301059485299")]
public Shipping shipping { get; set; }
}
the problem is in this part:
[JsonProperty(PropertyName = "XD1703301059485299")]
And the dynamic property name that I get from server...
This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:
XS12394124912841
The object is the null....
How can I resolve property name to be dynamic ? Can someone help me out?
P.S. This is the JSON response itself:
{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}
So I don't think this problem is as dynamic as it sounds. You can probably just convert to a dyanmic object and explicitly handle conversions.
Sample solution below. I inserted a few values to show conversion works as expected.
Add nuget package Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace Serialize
{
public class Shipping
{
[JsonProperty(PropertyName = "shipping_name")]
public String Name { get; set; }
[JsonProperty(PropertyName = "shipping_img")]
public String Img { get; set; }
[JsonProperty(PropertyName = "shipping_code")]
public String Code { get; set; }
}
public class Order
{
public Shipping shipping { get; set; }
[JsonProperty(PropertyName = "order_sn")]
public string SerialNumber { get; set; }
[JsonProperty(PropertyName = "order_status")]
public string Status { get; set; }
}
class Program
{
static void Main(string[] args)
{
/*
{
"status":1,
"msg": {
"dynamic_name": {
"order_sn": "12312313123123123",
"order_status":"0",
"shipping_info": [{
"shipping_name":"name",
"shipping_no":"",
"shipping_img":"img",
"shipping_code":"code",
"shipping_time":"",
"track_goods":""
}]
}
},
"errcode":0
}
* */
var raw = "{ \"status\":1, \"msg\":{\"dynamic_name\":{\"order_sn\":\"12312313123123123\",\"order_status\":\"0\",\"shipping_info\":[{\"shipping_name\":\"name\",\"shipping_no\":\"\",\"shipping_img\":\"img\",\"shipping_code\":\"code\",\"shipping_time\":\"\",\"track_goods\":\"\"}]}},\"errcode\":0}";
var incomingOrder = new Order();
// properties on dynamic objects are evaluated at runtime
dynamic msgJson = JObject.Parse(raw);
// you'll want exception handling around all of this
var order = msgJson.msg.dynamic_name;
// accessing properties is easy (if they exist, as these do)
incomingOrder.SerialNumber = order.order_sn;
incomingOrder.Status = order.order_status;
// JObject cast might not be necessary. need to check for array elements, etc.
// but it's simple to serialize into a known type
incomingOrder.shipping = ((JObject)(order.shipping_info[0])).ToObject<Shipping>();
}
}
}
Alternatively, if the property name is given at runtime, you can dereference properties with the indexer getter
dynamic msgJson = JObject.Parse(raw);
JObject order = msgJson.msg["XS12394124912841"];
incomingOrder.SerialNumber = order["order_sn"].ToObject<string>();
incomingOrder.Status = order["order_status"].ToObject<string>();
incomingOrder.shipping = order["shipping_info"][0].ToObject<Shipping>();
You can implement something like this with the help of System.Web.Helpers
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
dynamic data = Json.Decode(json);
Console.WriteLine(data["your_property"]);
}
Here sample.json contains your sample JSON response.

Unable to use JSON data with Newtonsoft.Json in WPF

I am retrieving data from office365 api. The response is in JSON format. I want to get data like Id, DisplayName etc. into variables but not getting the right way to do it. Following this link. I'm new to API and JSON. Will Appreciate pointers as well towards best learning links.Sample JSON below for listing sub folders of Inbox folder.
Response JSON data.
{"#odata.context":"https://outlook.office365.com/api/v1.0/$metadata#Me/Folders('Inbox')/ChildFolders","value":
[
{"#odata.id":"https://outlook.office365.com/api/v1.0/Users('sample.user#demosite.com')/Folders('AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1iMjllLTJmsdfsdfdDSFSDFDFDF=')",
"Id":"AAMkADBjMdfgdfgDFGDFGDFGdfGDFGDFGDFGGDzrACAAB4xqMmAAA=",
"DisplayName":"SampleFolder","ParentFolderId":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1sdsDFSDFSDFSDFSDFSDFDFDFrACAAAAAAEMAAA=","ChildFolderCount":0,"UnreadItemCount":8,"TotalItemCount":94},
{"#odata.id":"https://outlook.office365.com/api/v1.0/Users('sample.user#demosite.com')/Folders('AAMkADBjMGZiZGFlLTE4ZmEasdasdasdASDASDASDASDSADDASDASDAB4xqMnAAA=')",
"Id":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1iMjllLTJmOGZkNGRhZmIzNQAuAasdASDASDASDASEDASDASDxSEHjzrACAAB4xqMnAAA=",
"DisplayName":"AnotherSampleFolder","ParentFolderId":"AAMkADBjMGZiZGFlLTE4ZmEtNGRlOS1sdsDFSDFSDFSDFSDFSDFDFDFrACAAAAAAEMAAA=","ChildFolderCount":0,"UnreadItemCount":21,"TotalItemCount":75}
]
}
The C# code using to parse JSON and find the required data.
HttpResponseMessage response = httpClient.SendAsync(request).Result;
if (!response.IsSuccessStatusCode)
throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);
string content = response.Content.ReadAsStringAsync().Result;
JObject jResult = JObject.Parse(content);
if (jResult["odata.error"] != null)
throw new Exception((string)jResult["odata.error"]["message"]["value"]);
//Attempt one - using dynamic [NOT WORKING - getting NULL values in the variables]
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
var folderName = results.Id;
var folderId = results.Name;
//Attempt two - [Not working - Throwing exception -
//Object reference not set to an instance of an object.]
var folderID = (string)jResult["odata.context"]["odata.id"][0]["Id"];
First create a class for your json object
public class RootObject
{
[JsonProperty(PropertyName = "#odata.context")]
public string context { get; set; }
public List<Value> value { get; set; }
}
public class Value
{
[JsonProperty(PropertyName = "#odata.id")]
public string dataId { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string ParentFolderId { get; set; }
public int ChildFolderCount { get; set; }
public int UnreadItemCount { get; set; }
public int TotalItemCount { get; set; }
}
Then Json Convert the Json string to your RootObject if your are using Newtonsoft Json then Deserilaze by using
RootObject shortiee = JsonConvert.DeserializeObject<RootObject>("Your Json String");
private List<string> GetDisplayNames(JObject content)
{
var obj = Json.Parse(content);
var values = obj["value"].ToList();
var displayNames = new List<string>();
foreach (var value in values)
{
displayNames .Add(system["DisplayName"].ToString());
}
return displayNames;
}
This would return the names, for example, and you could do this for each value you need to retrieve. However, this does not require you to serialize/deserialize the json object before using it. It works, but is most likely not best practice.
if (jResult["odata.error"] != null)
throw new Exception((string)jResult["odata.error"]["message"]["value"]);
//Attempt one - using dynamic [NOT WORKING - getting NULL values in the variables]
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
Side note: There is no key called "odata.error" in your JSON data. So you're effectively calling something which will return null.
One of the ways to deserialise JSON is to create model classes for the objects you want to process and deserialise into them directly, eg. JsonConvert.DeserializeObject<Folder>(content). As you are talking to an Office365 API, you find documentation and examples here on how they are defined.
Taken your folder response as an example, your model for a single Folder could look like this:
public class Folder
{
[JsonProperty(PropertyName = "#odata.id")]
public string OdataId { get; set; }
public string Id { get; set; }
public string DisplayName { get; set; }
public string ParentFolderId { get; set; }
public int ChildFolderCount { get; set; }
public int UnreadItemCount { get; set; }
public int TotalItemCount { get; set; }
}
Note1: in your example, you get a response with list of folders, so have to adjust this accordingly.
Note2: you can use JsonProperty to define a mapping between a JSON property/key and a C# property as shwon for #odata.id.
However, you can also use the Outlook Client Library which would make it mostly unnecessary to deal with JSON data directly (which seems preferable, unless you have a very specific reason to deal with JSON directly).

Deserialization of Json without name fields

I need to deserialize the following Json, which according to Jsonlint.com is valid, but ive not come across this before or cannot find examples of similar Json and how to deal with it?
[1,"Bellegrove / Sherwood ","76705","486","Bexleyheath Ctr",1354565507000]
My current system with like this:
Data class:
[DataContract]
public class TFLCollection
{ [DataMember(Name = "arrivals")]
public IEnumerable<TFLB> TFLB { get; set; }
}
[DataContract]
public class TFLB
{
[DataMember]
public string routeName { get; set; }
[DataMember]
public string destination { get; set; }
[DataMember]
public string estimatedWait { get; set; }
}
Deserializer:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TFLCollection));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result)))
{ var buses = (TFLCollection)serializer.ReadObject(stream);
foreach (var bus in buses.TFLBuses)
{
StopFeed _item = new StopFeed();
_item.Route = bus.routeName;
_item.Direction = bus.destination;
_item.Time = bus.estimatedWait;
listBox1.Items.Add(_item);
My exsiting deserializer works with a full Json stream and iterates through it, but in my new Json I need to deserialize, it only have 1 item, so I wont need to iterate through it.
So is it possible to deserialize my Json example using a similar method than I currently do?
I would say that you are attempting to overcomplicate things. What you have is a perfectly formed json array of strings. If I were you I would deserialize that to an .net array first, and then write a 'mapper' function to copy the values across:
public TFLB BusRouteMapper(string[] input)
{
return new TFLB {
Route = input[x],
Direction = input[y],
};
}
And so on. Of course this assumes that you know what order your json is going to be in, but if you are attempting this in the first place then you must do!

Categories

Resources