I have a problem with parsing json.
The json data is here: http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e.
I created some classes with json2csharp, but search is null:
var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";
WebClient client = new WebClient();
var json = client.DownloadString(url);
var search = JsonConvert.DeserializeObject<ServiceResponse>(json);
public class Engine
{
public int FMEBuildNumber { get; set; }
public string FMEHostName { get; set; }
public string FMEInstanceName { get; set; }
public int currentJobID { get; set; }
public int maxTransactionResultFailure { get; set; }
public int maxTransactionResultSuccess { get; set; }
public int resultFailureCount { get; set; }
public int resultSuccessCount { get; set; }
public int transactionPort { get; set; }
}
public class Engines
{
public List<Engine> engine { get; set; }
}
public class ServiceResponse
{
public string requestURI { get; set; }
public string token { get; set; }
public Engines engines { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class RootObject
{
[JsonProperty("serviceResponse")]
public ServiceResponse ServiceResponse { get; set; }
}
How about going dynamic way using Json.Net? (without using any class generated by http://json2csharp.com/)
var url = "http://beta.fmeserver.com/fmerest/engines/.json?token=0ccfa0400b2d760fa3519baf18a557edb118356e";
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(url);
dynamic dynobj = JsonConvert.DeserializeObject(json);
foreach (var engine in dynobj.serviceResponse.engines.engine)
{
Console.WriteLine("{0} {1}", engine.FMEInstanceName, engine.transactionPort);
}
}
Related
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);
I apologize for this post because it may seem banal to some people. But I would like to understand the operation of the GET API, unfortunately, somehow I have not found an accessible tutorial. As the best way to learn from examples, could anyone show me how to get the values from the name tag in the easiest way? can be up to textBox.
In xml:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=xml
In json:
https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json
Code
public class Result
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
Result result = JsonConvert.DeserializeObject<Result>(json);
richTextBox1.Text = result.name;
}
}
Thank you in advance for your help.
You are missing various classes in order to get your JSON string Deserialized properly. Try like:
public class Results
{
public string id { get; set; }
public string name { get; set; }
public bool hasVariables { get; set; }
public List<string> children { get; set; }
public string levels { get; set; }
}
public class Links
{
public string first { get; set; }
public string self { get; set; }
public string next { get; set; }
public string last { get; set; }
}
public class JsonObject
{
public int totalRecords { get; set; }
public int page { get; set; }
public int pageSize { get; set; }
public Links links { get; set; }
public List<Results> results { get; set; }
}
And then use like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://bdl.stat.gov.pl/api/v1/subjects?lang=pl&format=json");
JsonObject result = JsonConvert.DeserializeObject<JsonObject>(json);
foreach (var res in result.results)
{
MessageBox.Show(res.name);
}
}
I have json as below:
{"data":[{"name":"123","pwd":123},{"name":"456","pwd":456},{"name":"789","pwd":789}],"duration":5309,"query":"myquery","timeout":300}
Using http://json2csharp.com/ I am deserialising it as below:
namespace Test
{
public class Info
{
public string name{ get; set; }
public string pwd{ get; set; }
}
public class Product
{
public Info[] data { get; set; }
public int duration { get; set; }
public string query { get; set; }
public int timeout { get; set; }
}
//code here, function start etc.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new
StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Product myprod = JsonConvert.DeserializeObject<Product>(result);
var results = myprod.data;
}
}
The value of results is {Test.Info[0]} where Test is my namespace name. How do I obtain the actual data?
Your Info class should be
public class Info
{
public string name { get; set; }
public int pwd { get; set; }
}
This should work
var testJson = "{\"data\":[{\"name\":\"123\",\"pwd\":123},{\"name\":\"456\",\"pwd\":456},{\"name\":\"789\",\"pwd\":789}],\"duration\":5309,\"query\":\"myquery\",\"timeout\":300}";
var product = JsonConvert.DeserializeObject<Product>(testJson);
I am using a wikipedia api which contains external links of all places from a wikipedia article. My wikipedia api call is:
https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json
I make c# classes for json object using JsonToCsharp as follows:
public class Geosearch
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public double lat { get; set; }
public double lon { get; set; }
public double dist { get; set; }
public string primary { get; set; }
public string type { get; set; }
public string name { get; set; }
public object dim { get; set; }
public string country { get; set; }
public string region { get; set; }
}
public class Query
{
public List<Geosearch> geosearch { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
}
My deserialization code is as follows.With this code I got only one Title. But I want to get all the title from this api. I know I should make a foreach loop, but could not get logic how to implement it.
static void Main(string[] args)
{
WebClient client = new WebClient();
var GeoResponse = client.DownloadString("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json");
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(GeoResponse);
var firstKey = json.query.geosearch.First().title;
Console.WriteLine(firstKey);
}
This works fine -
var o = new HttpClient();
var res = new StreamReader(o.GetStreamAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result).ReadToEnd() ;
var obj = JsonConvert.DeserializeObject<RootObject>(res).query.geosearch.Select(a => a.title).ToList();
// count == 500
obj.Foreach(a => Console.WriteLine(a));
I just modified my code and It is working perfectly.
var response = client.GetAsync("https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=10000&gspage=Berlin&gslimit=500&gsprop=type|name|dim|country|region|globe&format=json").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<RootObject>(responseString).query.geosearch.Select(a => a.title).ToList();
foreach (var item in obj)
{
Console.WriteLine(item);
}
}
}
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.