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);
Related
I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }
I’m working on UWP and I’m trying to parse this Json but can't understand why this code can't work please anyone can check it with me need help. Thank you. And there is a problem in getting the list variable (List).
Any help is appreciated.
namespace testapi2
{
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
jsonCall();
}
public async void jsonCall()
{
List<Result> listResult = new List<Result>();
var client = new HttpClient();
HttpResponseMessage response =
await client.GetAsync(new Uri("http://api-public.guidebox.com/v1.43/Tunisia/rKgEWJbFg0kgEHrcGXPKhPDo0XtTafyC/movies/all/250/250"));
client.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
var array = await response.Content.ReadAsStringAsync();
JsonArray ja = JsonValue.Parse(array).GetArray();
for (uint i = 0; i < ja.Count; i++)
{
//Debug.WriteLine(i);
Result result = new Result();
int id = Convert.ToInt32(ja.GetObjectAt(i).GetNamedValue("id"));
string title = ja.GetObjectAt(i).GetNamedString("title");
int release_year = Convert.ToInt32(ja.GetObjectAt(i).GetNamedNumber("release_year"));
int themoviedb = Convert.ToInt32(ja.GetObjectAt(i).GetNamedString("themoviedb"));
string original_title = ja.GetObjectAt(i).GetNamedString("original_title");
// List<object> alternate_titles = ja.GetObjectAt(i).GetNamedArray("alternate_titles");
string imdb = ja.GetObjectAt(i).GetNamedString("imdb");
bool pre_order = ja.GetObjectAt(i).GetNamedBoolean("pre_order");
bool in_theaters = ja.GetObjectAt(i).GetNamedBoolean("in_theaters");
string release_date = ja.GetObjectAt(i).GetNamedString("release_date");
string rating = ja.GetObjectAt(i).GetNamedString("rating");
int rottentomatoes = Convert.ToInt32(ja.GetObjectAt(i).GetNamedString("rottentomatoes"));
string freebase = ja.GetObjectAt(i).GetNamedString("freebase");
int wikipedia_id = Convert.ToInt32(ja.GetObjectAt(i).GetNamedString("wikipedia_id"));
string metacritic = ja.GetObjectAt(i).GetNamedString("metacritic");
string common_sense_media = ja.GetObjectAt(i).GetNamedString("common_sense_media");
string poster_120x171 = ja.GetObjectAt(i).GetNamedString("poster_120x171");
string poster_240x342 = ja.GetObjectAt(i).GetNamedString("poster_240x342");
string poster_400x570 = ja.GetObjectAt(i).GetNamedString("poster_400x570");
listResult.Add(result);
}
// Debug.WriteLine("hello", listResult);
list.ItemsSource = listResult;
}
}
}
Your api return a value of jsonObject type and you try to convert that to an array.
you can try this.
At first add Newtonsoft.Json from manage nuget package of add reference.
Now paste your json response to this site jsonToC# and add generated to classes to your project. For your reference api you will get 2 class like this.
public class Result
{
public int id { get; set; }
public string title { get; set; }
public int release_year { get; set; }
public int themoviedb { get; set; }
public string original_title { get; set; }
public List<object> alternate_titles { get; set; }
public string imdb { get; set; }
public bool pre_order { get; set; }
public bool in_theaters { get; set; }
public string release_date { get; set; }
public string rating { get; set; }
public int rottentomatoes { get; set; }
public string freebase { get; set; }
public int wikipedia_id { get; set; }
public string metacritic { get; set; }
public string common_sense_media { get; set; }
public string poster_120x171 { get; set; }
public string poster_240x342 { get; set; }
public string poster_400x570 { get; set; }
}
public class RootObject
{
public int total_results { get; set; }
public int total_returned { get; set; }
public List<Result> results { get; set; }
}
then add following code & will get all data at result.
var json = await response.Content.ReadAsStringAsync();
var result= JsonConvert.DeserializeObject<RootObject>(json);
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);
I have an API which validates the cellphones and returns a JSON data. Now I want to read the JSON and show in a table format.
API Call,
protected void CallAPI()
{
WebClient wsClient = new WebClient();
string url = apiUrl;
string response = string.Empty;
string serialkey = txtserialNumber.Text;
WebRequest req = WebRequest.Create(#"https://alt.computechsos.com/api/v1/xx");
req.Method = "POST";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:#password"));
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
WebHeaderCollection header = resp.Headers;
string responseText = string.Empty;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(resp.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
}
The 'responseText' now contains the following JSON
Json returned Response:
{"ios_info":{"serialNumber":"F2LLMBNJXXXQ","imeiNumber":"0138840041323XX","meid":"","iccID":"890141042764009604XX","firstUnbrickDate":"11\/27\/13","lastUnbrickDate":"11\/27\/13","unbricked":"true","unlocked":"false","productVersion":"7.1.1","initialActivationPolicyID":"23","initialActivationPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","appliedActivationPolicyID":"23","appliedActivationDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","nextTetherPolicyID":"23","nextTetherPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","macAddress":"ACFDEC6C9XXX","bluetoothMacAddress":"AC:FD:EC:6C:98:8B","partDescription":"IPHONE 5S SPACE GRAY 64GB-USA"},"product_info":{"serialNumber":"F2LLMBNJXXXQ","warrantyStatus":"Apple Limited Warranty","coverageEndDate":"11\/25\/14","coverageStartDate":"11\/26\/13","daysRemaining":"528","estimatedPurchaseDate":"11\/26\/13","purchaseCountry":"United States","registrationDate":"11\/26\/13","imageURL":"http:\/\/service.info.apple.com\/parts\/service_parts\/na.gif","explodedViewURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","manualURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","productDescription":"iPhone 5S","configDescription":"IPHONE 5S GRAY 64GB GSM","slaGroupDescription":"","contractCoverageEndDate":"11\/25\/15","contractCoverageStartDate":"11\/26\/13","contractType":"C1","laborCovered":"Y","limitedWarranty":"Y","partCovered":"Y","notes":"Covered by AppleCare+ - Incidents Available","acPlusFlag":"Y","consumerLawInfo":{"serviceType":"","popMandatory":"","allowedPartType":""}}}
How to read this JSON and show data in table format?
Use Json-Net to deserialize the response. To generate classes, you can use this generator which takes a Json input and outputs the C# classes associated.
//....
var responseObject = JsonConvert.DeserializeObject<RootObject>(responseText);
}
public class IosInfo
{
public string serialNumber { get; set; }
public string imeiNumber { get; set; }
public string meid { get; set; }
public string iccID { get; set; }
public string firstUnbrickDate { get; set; }
public string lastUnbrickDate { get; set; }
public string unbricked { get; set; }
public string unlocked { get; set; }
public string productVersion { get; set; }
public string initialActivationPolicyID { get; set; }
public string initialActivationPolicyDetails { get; set; }
public string appliedActivationPolicyID { get; set; }
public string appliedActivationDetails { get; set; }
public string nextTetherPolicyID { get; set; }
public string nextTetherPolicyDetails { get; set; }
public string macAddress { get; set; }
public string bluetoothMacAddress { get; set; }
public string partDescription { get; set; }
}
public class ConsumerLawInfo
{
public string serviceType { get; set; }
public string popMandatory { get; set; }
public string allowedPartType { get; set; }
}
public class ProductInfo
{
public string serialNumber { get; set; }
public string warrantyStatus { get; set; }
public string coverageEndDate { get; set; }
public string coverageStartDate { get; set; }
public string daysRemaining { get; set; }
public string estimatedPurchaseDate { get; set; }
public string purchaseCountry { get; set; }
public string registrationDate { get; set; }
public string imageURL { get; set; }
public string explodedViewURL { get; set; }
public string manualURL { get; set; }
public string productDescription { get; set; }
public string configDescription { get; set; }
public string slaGroupDescription { get; set; }
public string contractCoverageEndDate { get; set; }
public string contractCoverageStartDate { get; set; }
public string contractType { get; set; }
public string laborCovered { get; set; }
public string limitedWarranty { get; set; }
public string partCovered { get; set; }
public string notes { get; set; }
public string acPlusFlag { get; set; }
public ConsumerLawInfo consumerLawInfo { get; set; }
}
public class RootObject
{
public IosInfo ios_info { get; set; }
public ProductInfo product_info { get; set; }
}
you need to have a class with all the properties which your json string contains , say for example you have that class called Jsondeserial
JsonDeserial obj = JsonConvert.DeserializeObject<JsonDeserial>(jsonstring);
this will convert your json string to that object values
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.