JSON parsing C# no name variable - c#

I'm trying to deserialize a Json String to a object but I only get 0 and null back.
Here is my code:
string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var serializer = new DataContractJsonSerializer(typeof(LandRootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (LandRootObject)serializer.ReadObject(ms);
public class LandRootObject
{
public int page { get; set; }
public int pages { get; set; }
public string per_page { get; set; }
public int total { get; set; }
[DataMember]
public List<Land> land { get; set; }
}
Thanks!

I have tested this method and it's working.
Your entity classes. (I did not code all these classes. They are code generated using paste special.)
public class LandRootObject
{
public int page { get; set; }
public int pages { get; set; }
public string per_page { get; set; }
public int total { get; set; }
}
public class LandBodyObject
{
public string id { get; set; }
public string iso2Code { get; set; }
public string name { get; set; }
public Region region { get; set; }
public Adminregion adminregion { get; set; }
public Incomelevel incomeLevel { get; set; }
public Lendingtype lendingType { get; set; }
public string capitalCity { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
public class Region
{
public string id { get; set; }
public string value { get; set; }
}
public class Adminregion
{
public string id { get; set; }
public string value { get; set; }
}
public class Incomelevel
{
public string id { get; set; }
public string value { get; set; }
}
public class Lendingtype
{
public string id { get; set; }
public string value { get; set; }
}
Then the deserialisation method. Your Json has two parts. So I am splitting it in to 2 for deserialisation.
string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var parts = result.Split(new[] {",["}, StringSplitOptions.None);
if (parts.Length > 1)
{
var header = parts[0].Replace("[", "");
var jsonHeader = JsonConvert.DeserializeObject<LandRootObject>(header);
var body = "[" + parts[1].Replace("]]","]");
var jsonBody = JsonConvert.DeserializeObject<List<LandBodyObject>>(body);
}

Use List type
var serializer = new DataContractJsonSerializer(typeof(List<LandRootObject>));
// ...
var data = (List<LandRootObject>)serializer.ReadObject(ms);
Edit:
Now I see - your json array consists of 2 different elements. I suppose its [RootObject, Lands]. You better use the Newtonsoft.Json to deserialize the object.
var str = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var arr = JArray.Parse(str);
var rootJson = arr.ElementAt(0).ToString();
var root = JsonConvert.DeserializeObject<LandRootObject>(rootJson);
var landsJson = arr.ElementAt(1).ToString();
root.Lands = JsonConvert.DeserializeObject<List<Land>>(landsJson);

tryto change the above code to following
ms.Position = 0; // change only this line
var data = (LandRootObject)serializer.ReadObject(ms);

Related

How to read sections of JSON document?

I have a JSON document and I want to access the details of the STATUS SECTION but it keeps returning null.
JSON Data is as shown:
{
"results":[
{
"messageId":"15712480583306574",
"to":"",
"from":"TestServer",
"sentAt":"2019-10-16T17:47:38.368+0000",
"doneAt":"2019-10-16T17:47:38.370+0000",
"smsCount":1,
"mccMnc":"null",
"price":{
"pricePerMessage":0.0,
"currency":"USD"
},
"status":{
"groupId":5,
"groupName":"REJECTED",
"id":8,
"name":"REJECTED_PREFIX_MISSING",
"description":"Number prefix missing"
},
"error":{
"groupId":0,
"groupName":"OK",
"id":0,
"name":"NO_ERROR",
"description":"No Error",
"permanent":false
}
}
]
}
C# Code is:
string JsonData = response.Content.ToString();
dynamic results = JsonConvert.DeserializeObject<dynamic>(JsonData);
var statuses = results.status;
foreach(var stat in statuses) {
string groupname = stat.groupName.Value;
string name = stat.name.Value;
string description = stat.description.Value;
}
It keeps returning null, How can I access these members? I am using Newtonsoft.
If you want to access the status object property you need to rewrite your whole code.
string JsonData = response.Content.ToString();
var input = JObject.Parse(str);
var results = input["results"].Children();
var status = results.First()["status"];
string groupname = status["groupName"].ToString();
string name = status["name"].ToString();
string description = status["description"].ToString();
Console.WriteLine(groupname);
Console.WriteLine(name);
Console.WriteLine(description);
The result in Console
REJECTED
REJECTED_PREFIX_MISSING
Number prefix missing
But I would rather use concrete class. You need to create multiple classes. Here is good example.
public class Envelope
{
public List<Item> Results { get; set; }
}
public class Item
{
public Status Status { get; set; }
}
public class Status
{
public int GroupId { get; set; }
public string GroupName { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
After that the usage is much simpler.
string JsonData = response.Content.ToString();
MyEnvelope envelope = JsonConvert.DeserializeObject<MyEnvelope>(JsonData);
var status = envelope.results[0].status;
Console.WriteLine(status.GroupName);
Console.WriteLine(status.Name);
Console.WriteLine(status.Description);
Finest Option: Create A model for the JSON.
public class Price
{
public double pricePerMessage { get; set; }
public string currency { get; set; }
}
public class Status
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
}
public class Error
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool permanent { get; set; }
}
public class Result
{
public string messageId { get; set; }
public string to { get; set; }
public string from { get; set; }
public DateTime sentAt { get; set; }
public DateTime doneAt { get; set; }
public int smsCount { get; set; }
public string mccMnc { get; set; }
public Price price { get; set; }
public Status status { get; set; }
public Error error { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Then do RootObject results = JsonConvert.DeserializeObject<RootObject>(JsonData);
Fair Option: Get the exact JToken you want.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonData = "{\"results\":[{\"messageId\":\"15712480583306574\",\"to\":\"\",\"from\":\"TestServer\",\"sentAt\":\"2019-10-16T17:47:38.368+0000\",\"doneAt\":\"2019-10-16T17:47:38.370+0000\",\"smsCount\":1,\"mccMnc\":\"null\",\"price\":{\"pricePerMessage\":0.0,\"currency\":\"USD\"},\"status\":{\"groupId\":5,\"groupName\":\"REJECTED\",\"id\":8,\"name\":\"REJECTED_PREFIX_MISSING\",\"description\":\"Number prefix missing\"},\"error\":{\"groupId\":0,\"groupName\":\"OK\",\"id\":0,\"name\":\"NO_ERROR\",\"description\":\"No Error\",\"permanent\":false}}]}";
JObject jObject = JObject.Parse(jsonData);
Console.WriteLine(jObject.SelectToken("results[0].status"));
}
}

Converting an abnormal JSON string to List<class>

I came a cross a web service from another company that returns an abnormal JSON string.
This is what the JSON look like:
["TERMINAL_NO","METER_NO","RAMZE_RAYANEH_SHENASE_GHABZ","PARVANDEH_ESHTERAK","POWER_UTILITY","CT_RATIO","PT_RATIO","NAME_","PART","CUSTOMER_ID","X_POS","Y_POS","DATE_NUM","HOUR_NUM","MONTH_","DAY_","YEAR_","DAY_WEEK","MONTH_DAY","DATE_HOUR","ACTIVE_ENERGY_PLUS_TOTAL","ACTIVE_ENERGY_PLUS_TARIF_1","ACTIVE_ENERGY_PLUS_TARIF_2","ACTIVE_ENERGY_PLUS_TARIF_3","ACTIVE_ENERGY_PLUS_TARIF_4","ACTIVE_ENERGY_MINUS_TOTAL","ACTIVE_ENERGY_MINUS_TARIF_1","ACTIVE_ENERGY_MINUS_TARIF_2","ACTIVE_ENERGY_MINUS_TARIF_3","ACTIVE_ENERGY_MINUS_TARIF_4","REACTIVE_ENERGY_PLUS_TOTAL","REACTIVE_ENERGY_PLUS_TARIF_1","REACTIVE_ENERGY_PLUS_TARIF_2","REACTIVE_ENERGY_PLUS_TARIF_3","REACTIVE_ENERGY_PLUS_TARIF_4","REACTIVE_ENERGY_MINUS_TOTAL","REACTIVE_ENERGY_MINUS_TARIF_1","REACTIVE_ENERGY_MINUS_TARIF_2","REACTIVE_ENERGY_MINUS_TARIF_3","REACTIVE_ENERGY_MINUS_TARIF_4","VOLTAGE_PHASE_A","VOLTAGE_PHASE_B","VOLTAGE_PHASE_C","CURRENT_PHASE_A","CURRENT_PHASE_B","CURRENT_PHASE_C","POWER_ACTIV_AVG","POWER_ACTIV_MIN","POWER_ACTIV_MAX","POWER_REACT_AVG","POWER_REACT_MIN","POWER_REACT_MAX","POWER_FACTOR_PHASE_A","POWER_FACTOR_PHASE_B","POWER_FACTOR_PHASE_C","READ_FLAG"],
["039530059094","039530059094","8448430104225","2420815","\u06a9\u0646\u062a\u0648\u0631\u0647\u0627\u06cc \u062f\u06cc\u0645\u0627\u0646\u062f\u06cc \u0627\u0633\u062a\u0627\u0646 \u062a\u0647\u0631\u0627\u0646","100\/5","1\/1","Ali Falahi","\u06af\u0644\u0633\u062a\u0627\u0646","2420815",null,null,"13980607","0","06","07","1398","\u067e\u0646\u062c \u0634\u0646\u0628\u0647","0607","0607.0",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"OFFLINE"],
["039530059094","039530059094","8448430104225","2420815","\u06a9\u0646\u062a\u0648\u0631\u0647\u0627\u06cc \u062f\u06cc\u0645\u0627\u0646\u062f\u06cc \u0627\u0633\u062a\u0627\u0646 \u062a\u0647\u0631\u0627\u0646","100\/5","1\/1","Ali Falahi","\u06af\u0644\u0633\u062a\u0627\u0646","2420815",null,null,"13980607","1","06","07","1398","\u067e\u0646\u062c \u0634\u0646\u0628\u0647","0607","0607.1",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"OFFLINE"]
The first row of data is the name of the columns and the rest is the data.
Since I can't tell them to change their data format, how can I convert this to list of class or anything like list of key-value pair with relative columns?
It depends on how you plan to use the data. My guess is that you need to be able to pair the elements of the first row with the data in the 1st thru nth rows. So perhaps the desired output is a list of dictionaries.
If that is the case, I suggest you parse it as JSON (not as a CSV-- the escaping rules are different) then map the fields into the data structure you need. For example:
var array = JsonConvert.DeserializeAnonymousType("[" + input + "]" , (string[][])null);
Console.WriteLine("There were {0} rows with {1} columns", array.Length, array[0].Length);
var list = new List<Dictionary<string,string>>();
for (var i = 1; i<= array.GetUpperBound(0); i++)
{
var dictionary = array[0]
.Zip(array[i], (l,r) => new KeyValuePair<string,string>(l,r))
.ToDictionary( pair => pair.Key, pair => pair.Value);
list.Add(dictionary);
}
Console.WriteLine("We now have a list of {0} rows", list.Count);
for (int i=0; i<list.Count; i++)
{
Console.WriteLine("\r\nHere is row {0}\r\n", i);
var dictionary = list[i];
foreach (var key in dictionary.Keys)
{
Console.WriteLine("{0} = {1}", key, dictionary[key]);
}
}
Output looks like this:
There were 3 rows with 56 columns
We now have a list of 2 rows
Here is row 0
TERMINAL_NO = 039530059094
METER_NO = 039530059094
RAMZE_RAYANEH_SHENASE_GHABZ = 8448430104225
PARVANDEH_ESHTERAK = 2420815
POWER_UTILITY = ???????? ??????? ????? ?????
CT_RATIO = 100/5
PT_RATIO = 1/1
NAME_ = Ali Falahi
PART = ??????
CUSTOMER_ID = 2420815
X_POS =
Y_POS =
DATE_NUM = 13980607
HOUR_NUM = 0
MONTH_ = 06
DAY_ = 07
YEAR_ = 1398
DAY_WEEK = ??? ????
MONTH_DAY = 0607
DATE_HOUR = 0607.0
ACTIVE_ENERGY_PLUS_TOTAL =
ACTIVE_ENERGY_PLUS_TARIF_1 =
ACTIVE_ENERGY_PLUS_TARIF_2 =
ACTIVE_ENERGY_PLUS_TARIF_3 =
ACTIVE_ENERGY_PLUS_TARIF_4 =
ACTIVE_ENERGY_MINUS_TOTAL =
Here's a link to a working Fiddle
If you want to get a nice list of classes out the other end there's a bit of work to transform your almost-CSV style JSON to something that can be deserialized to a list of typed objects, e.g.:
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json; // Install-Module Newtonsoft.JSON
namespace StackOverflow
{
public class PowerReading
{
[JsonProperty("TERMINAL_NO")]
public string TerminalNumber { get; set; }
[JsonProperty("METER_NO")]
public string MeterNumber { get; set; }
public string RAMZE_RAYANEH_SHENASE_GHABZ { get; set; }
public string PARVANDEH_ESHTERAK { get; set; }
[JsonProperty("POWER_UTILITY")]
public string PowerUtility { get; set; }
public string CT_RATIO { get; set; }
public string PT_RATIO { get; set; }
[JsonProperty("NAME_")]
public string Name { get; set; }
public string Part { get; set; }
[JsonProperty("CUSTOMER_ID")]
public string CustomerId { get; set; }
[JsonProperty("X_POS")]
public string XPos { get; set; }
[JsonProperty("Y_POS")]
public string YPos { get; set; }
public string DATE_NUM { get; set; }
public string HOUR_NUM { get; set; }
public string MONTH_ { get; set; }
public string DAY_ { get; set; }
public string YEAR_ { get; set; }
public string DAY_WEEK { get; set; }
public string DATE_HOUR { get; set; }
public string ACTIVE_ENERGY_PLUS_TOTAL { get; set; }
public string ACTIVE_ENERGY_PLUS_TARRIF1 { get; set; }
public string ACTIVE_ENERGY_PLUS_TARRIF2 { get; set; }
public string ACTIVE_ENERGY_PLUS_TARRIF3 { get; set; }
public string ACTIVE_ENERGY_PLUS_TARRIF4 { get; set; }
public string ACTIVE_ENERGY_MINUS_TOTAL { get; set; }
public string ACTIVE_ENERGY_MINUS_TARRIF1 { get; set; }
public string ACTIVE_ENERGY_MINUS_TARRIF2 { get; set; }
public string ACTIVE_ENERGY_MINUS_TARRIF3 { get; set; }
public string ACTIVE_ENERGY_MINUS_TARRIF4 { get; set; }
public string REACTIVE_ENERGY_PLUS_TOTAL { get; set; }
public string REACTIVE_ENERGY_PLUS_TARRIF1 { get; set; }
public string REACTIVE_ENERGY_PLUS_TARRIF2 { get; set; }
public string REACTIVE_ENERGY_PLUS_TARRIF3 { get; set; }
public string REACTIVE_ENERGY_PLUS_TARRIF4 { get; set; }
public string REACTIVE_ENERGY_MINUS_TOTAL { get; set; }
public string REACTIVE_ENERGY_MINUS_TARRIF1 { get; set; }
public string REACTIVE_ENERGY_MINUS_TARRIF2 { get; set; }
public string REACTIVE_ENERGY_MINUS_TARRIF3 { get; set; }
public string REACTIVE_ENERGY_MINUS_TARRIF4 { get; set; }
public string VOLTAGE_PHASE_A { get; set; }
public string VOLTAGE_PHASE_B { get; set; }
public string VOLTAGE_PHASE_C { get; set; }
public string CURRENT_PHASE_A { get; set; }
public string CURRENT_PHASE_B { get; set; }
public string CURRENT_PHASE_C { get; set; }
public string POWER_ACTIV_AVG { get; set; }
public string POWER_ACTIV_MIN { get; set; }
public string POWER_ACTIV_MAX { get; set; }
public string POWER_REACT_AVG { get; set; }
public string POWER_REACT_MIN { get; set; }
public string POWER_REACT_MAX { get; set; }
public string POWER_FACTOR_PHASE_A { get; set; }
public string POWER_FACTOR_PHASE_B { get; set; }
public string POWER_FACTOR_PHASE_C { get; set; }
public string READ_FLAG { get; set; }
}
class MainClass
{
public static void Main(string[] args)
{
//First JSON pass: fix the JSON up enough to read in as an array of string arrays.
var badJson = System.IO.File.ReadAllText("web_service.json");
var arrayOfStringArrays = JsonConvert.DeserializeObject<string[][]>("[" + badJson + "]");
//Use the first row as column headings (aka Object Property Names).
var headings = arrayOfStringArrays.Take(1).FirstOrDefault();
//Convert the remaining rows to a List of Dictionary<string,string> objects.
var data = arrayOfStringArrays
.Skip(1)
.Select(row =>
{
var colIndex = 0;
var dictionary = new System.Collections.Generic.Dictionary<string, string>();
row.ToList().ForEach(col => dictionary.Add(headings[colIndex++], col));
return dictionary;
});
//Serialize the List<Dictionary<string,string>> back to JSON.
var goodJson = JsonConvert.SerializeObject(data);
//Now we can deserialize the JSON to list of typed objects.
var powerReadings = JsonConvert.DeserializeObject<IList<PowerReading>>(goodJson);
}
}
}
The JSON is like a 2D array, except it is missing the start and ends of the outer array. You could restore them, and then parse as a 2D string array:
var result = JsonConvert.DeserializeObject<string[][]>(jsonMessage);

Invalid Json error during json object convert

I am trying to convert a json response value to c# class value. But when i try to pass into JsonDeserializer that response it throwing error: Invalid Json. Bellow the code example is provided. Also note i am using RestSharp to make that url call. And the example url also provided bellow:
response url: http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548
string url = "http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var deserializer = new JsonDeserializer();
var wmr = deserializer.Deserialize<WallMartData>(response);
Model class generated by http://json2csharp.com/
namespace WebApplication2.ViewModels
{
public class Attributes
{
public string color { get; set; }
public string productUrlText { get; set; }
public string uniqueProductId { get; set; }
}
public class GiftOptions
{
}
public class ImageEntity
{
public string thumbnailImage { get; set; }
public string mediumImage { get; set; }
public string largeImage { get; set; }
public string entityType { get; set; }
}
public class WallMartData
{
public int itemId { get; set; }
public int parentItemId { get; set; }
public string name { get; set; }
public double msrp { get; set; }
public double salePrice { get; set; }
public string upc { get; set; }
public string categoryPath { get; set; }
public string shortDescription { get; set; }
public string longDescription { get; set; }
public string brandName { get; set; }
public string thumbnailImage { get; set; }
public string mediumImage { get; set; }
public string largeImage { get; set; }
public string productTrackingUrl { get; set; }
public double standardShipRate { get; set; }
public string color { get; set; }
public bool marketplace { get; set; }
public string modelNumber { get; set; }
public string sellerInfo { get; set; }
public string productUrl { get; set; }
public string customerRating { get; set; }
public int numReviews { get; set; }
public string customerRatingImage { get; set; }
public string categoryNode { get; set; }
public string rhid { get; set; }
public bool bundle { get; set; }
public bool clearance { get; set; }
public bool preOrder { get; set; }
public string stock { get; set; }
public Attributes attributes { get; set; }
public string addToCartUrl { get; set; }
public string affiliateAddToCartUrl { get; set; }
public bool freeShippingOver35Dollars { get; set; }
public GiftOptions giftOptions { get; set; }
public List<ImageEntity> imageEntities { get; set; }
public string offerType { get; set; }
public bool availableOnline { get; set; }
}
}
The response sent is a json array so all you need to do is change the last line to:
var wmr = deserializer.Deserialize<List<WallMartData>>(response);
Basically deserialize into a list of your model.
I've to guess, but the URL sends an array, not a single object of WallMartData.
Try something like this:
List<string> tmp = new List<string>();
using (var sr = new StreamReader("C:\\Temp\\tst.txt")) // tst.txt contains the url-response
{
while(!sr.EndOfStream)
tmp.Add(sr.ReadLine());
}
WallMartData[] x = JsonConvert.DeserializeObject<WallMartData[]>(string.Join("\n", tmp));
In your case it would be:
string url = "http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var deserializer = new JsonDeserializer();
var wmr = deserializer.Deserialize<WallMartData[]>(response); // See the bracer here ;-)
It return a List or Array
Try this
string url = "http://api.walmartlabs.com/v1/items?apiKey=3zmwbajjf4ugzqhdtgsf59ac&upc=029986182548";
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var deserializer = new JsonDeserializer();
var wmr = deserializer.Deserialize<List<WallMartData>>(response);

How do you get the selling_price? (Xamarin Forms)

This is my code:
dynamic resultObject = JsonConvert.DeserializeObject(Result);
string final = JsonConvert.SerializeObject(resultObject);
This my the result of final (JSON):
How do get the selling_price field? like doing final.selling_price?
My class:
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
} // itemPriceJson
You're not deserializing the json to a dynamic object properly. First of all, it's an array, not an object.
So, try it like this:
dynamic resultObject = JArray.Parse(Result); //Dynamic object.
var sellingPrice = resultObject[0].selling_price; //Get the selling price. Could also use some casting here.
You should change your class to
public class ItemPriceJson {
public int item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public int price_level_id { get; set; }
public string price_level_code { get; set; }
public int selling_price { get; set; }
} // itemPriceJson
and deserialize it with
var results = JsonConvert.DeserializeObject<List<ItemPriceJson>>( Result );
because the json result contains an array of objects and so you need a collection for deserialization
Create a POCO class which describes the object for example;
public class MyItemObject
{
public string item_price_id { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
}
Then use JsonConvert to deserialize a instance of the object.
var result = JsonConvert.DeserializeObject<MyItemObject>(json);
EDIT
As json is a list/collection deserialize as a list type;
var listResult = JsonConvert.DeserializeObject<List<MyItemObject>>(json);
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
}
And you can use the Newtonsoft json library
var result = JsonConvert.DeserializeObject<List<ItemPriceJson>>(jsonstring);

Converting Object to JSON string in c#,WP7

I am facing problem when am trying to get a JSON string like
[{Key:{key:value,key:value,key:value,key:value},
key: [{key:value,key:value,key:value,key:value}]
in C#.
my class structure is like this
public class wideeye
{
public listing listing { get; set; }
public listing_images[] listing_images { get; set; }
}
public class listing
{
public string category { get; set; }
public string city { get; set; }
public string country { get; set; }
public string created_at { get; set; }
public string current_publish_date { get; set; }
public string details { get; set; }
public string id { get; set; }
public string industry { get; set; }
public string list_exp_date { get; set; }
public string list_price { get; set; }
public string list_start_date { get; set; }
public string make { get; set; }
public string model { get; set; }
public string open_bid { get; set; }
public string state { get; set; }
public string status { get; set; }
public string title { get; set; }
public string updated_at { get; set; }
public string year { get; set; }
}
public class listing_images
{
public string created_at { get; set; }
public string id { get; set; }
public string listing_id { get; set; }
public string listing_image_content_type { get; set; }
public string listing_image_file_name { get; set; }
public int listing_image_file_size { get; set; }
public string listing_image_updated_at { get; set; }
public string updated_at { get; set; }
}
}
and the code is
listing bid1 =
new listing { category = "electronics", city = "BBSR" };
listing_images bid2 =
new listing_images { created_at = "Instrumentation", id = "10" };
List<listing> obid1 = new List<listing>() { bid1};
List<listing_images> obid2 = new List<listing_images>() { bid2 };
//DataContractJsonSerializer serializer = null;
string sJSON = JsonConvert.SerializeObject(obid1);
string sJSONw = JsonConvert.SerializeObject(obid2);
DataContractJsonSerializer class is very handy.
Add references to System.Runtime.Serialization.dll and System.Servicemodel.Web.dll to your project.
using System.Runtime.Serialization.Json;
...
...
...
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer sr = new DataContractJsonSerializer(obj.GetType());
sr.WriteObject(stream, obj);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string jsonResult = reader.ReadToEnd();
Of course do proper exceptions handling.
I vote for using JSON.net # http://json.codeplex.com/ Its being adopted by Microsoft and its more efficient that the DataContractJsonSerializer
example of use here : http://james.newtonking.com/projects/json/help/
or if not use the Javascript Serializer
protected static string JsonSerialize(Object obj)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = int.MaxValue };
var json = serializer.Serialize(obj);
return json;
}
Would have left this as a comment but was rather cumbersome:
add a reference to System.Web.MVC to your project and then create the JSON like this:
var jsonOutput = Json(obid1);
This is how I generate JSON in MVC controllers for my AJAX calls. Have not tried it in a Windows mobile app though.
Just a thought.

Categories

Resources