Converting Object to JSON string in c#,WP7 - c#

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.

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"));
}
}

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);

Difference JSON deserialisation 'online site' vs 'paste into Visual studio'

I try to generate C# class with JSON datas. This datas are on this site
Method 1 : I used this online builder builder online
Method 2 : I used special paste to JSON into Visual Studio 2015 (like explain here)
Conclusion: not same result! Why?
Result with online site :
public class Translations
{
public string de { get; set; }
public string es { get; set; }
public string fr { get; set; }
public string ja { get; set; }
public string it { get; set; }
}
public class RootObject
{
public string name { get; set; }
public List<string> topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public List<object> callingCodes { get; set; }
public string capital { get; set; }
public List<object> altSpellings { get; set; }
public string relevance { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public List<object> latlng { get; set; }
public string demonym { get; set; }
public double? area { get; set; }
public double? gini { get; set; }
public List<string> timezones { get; set; }
public List<object> borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public List<string> currencies { get; set; }
public List<object> languages { get; set; }
public Translations translations { get; set; }
}
Result with special paste of Visual Studio :
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public string[] topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public string[] callingCodes { get; set; }
public string capital { get; set; }
public string[] altSpellings { get; set; }
public string relevance { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public float?[] latlng { get; set; }
public string demonym { get; set; }
public float? area { get; set; }
public float? gini { get; set; }
public string[] timezones { get; set; }
public string[] borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public string[] currencies { get; set; }
public string[] languages { get; set; }
public Translations translations { get; set; }
}
public class Translations
{
public string de { get; set; }
public string es { get; set; }
public string fr { get; set; }
public string ja { get; set; }
public string it { get; set; }
}
Worse! The deserialisation with VS code does'nt work!
Code for deserialise :
string url = #"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<Rootobject>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<Rootobject> countries = (IEnumerable<Rootobject>)serializer.ReadObject(memo);
int i = countries.Count();
}
Console.Read();
Have you an idea of this difference? Bug VS?
In the second example, Visual Studio actually wraps the "root object" with yet another root object that contains an array of Class1.
Since the payload data structure root is an array, not an object, this would appear to be a bug, provided you used the correct payload to generate the structure.
As a result, just replace Rootobject references with Class1.
string url = #"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(IEnumerable<Class1>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<Class1> countries = (IEnumerable<Class1>)serializer.ReadObject(memo);
int i = countries.Count();
}
Console.Read();
As an aside, you should really switch to a more modern serializer such as Newtonsoft JSON.NET.

JSON parsing C# no name variable

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);

Json response with several tables(?)

How do I parse a Json response in form of:
www.extradelar.se/match
If I understand this response right, its an array of three responses, how do I parse them in this case? How do I Deserialize this into my RootObject?
I am not sure if its due to copy paste but the json provided was not valid:
Using http://jsonlint.com/ you can validate an indent your json:
Once you indent, it is easier to look at .
The above JSON is array of array where each one contains an object.
It is a little odd for usual JSON, but maybe you have your own reasons.
Using libraries like JSON.net you can easily parse that data into C# objects.
Hope this helps
EDIT:
POCO Class:
public class RootObject
{
public string match_id { get; set; }
public string no_repick { get; set; }
public string no_agi { get; set; }
public string drp_itm { get; set; }
public string no_timer { get; set; }
public string rev_hs { get; set; }
public string no_swap { get; set; }
public string no_int { get; set; }
public string alt_pick { get; set; }
public string veto { get; set; }
public string shuf { get; set; }
public string no_str { get; set; }
public string no_pups { get; set; }
public string dup_h { get; set; }
public string ap { get; set; }
public string br { get; set; }
public string em { get; set; }
public string cas { get; set; }
public string rs { get; set; }
public string nl { get; set; }
public string officl { get; set; }
public string no_stats { get; set; }
public string ab { get; set; }
public string hardcore { get; set; }
public string dev_heroes { get; set; }
public string verified_only { get; set; }
public string gated { get; set; }
}
JSON.NET
private string getMatchId()
{
using (var webClient = new System.Net.WebClient())
{
const string url = #"http://www.extradelar.se/match";
var json = webClient.DownloadString(url);
var matchen = JsonConvert.DeserializeObject<List<List<RootObject>>>(json);
var matchId = matchen[0][0].match_id;
return matchId;
}
}

Categories

Resources