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