I am not getting JsonConvert.DeserializeObject to work for me.
I get the correct value in JSON from the service. Not finding anything online for this, would appreciate a little help here :)
Here is my code:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void tbPlate_OnServerChange(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(tbPlate.Text))
{
var _res = Responses(tbPlate.Text);
if (_res.Vehicles != null)
{
lblTestText.Text = _res.Vehicles.FirstOrDefault(r => r.regNr == tbPlate.Text)?.ToString();
}
else
{
lblTestText.Text = "No vehicle data";
}
}
}
private static VehicleResults Responses(string regNr)
{
var _jSon = "";
var _url = #"http://apis.is/car";
var _res = new VehicleResults();
var _request = (HttpWebRequest)WebRequest.Create($"{_url}?number={regNr}");
var _response = _request.GetResponse();
using (var _responseStream = _response.GetResponseStream())
{
var _reader = new StreamReader(_responseStream, Encoding.UTF8);
_jSon = _reader.ReadToEnd();
}
_res = JsonConvert.DeserializeObject<VehicleResults>(_jSon);
return _res;
}
}
public class VehicleResponse
{
[JsonProperty("registryNumber")]
public string regNr { get; set; }
public string number { get; set; }
public string factoryNumber { get; set; }
public string type { get; set; }
public string subType { get; set; }
public string color { get; set; }
public string registeredAt { get; set; }
public string status { get; set; }
public string nextCheck { get; set; }
public string pollution { get; set; }
public string weight { get; set; }
}
public class VehicleResults
{
public List<VehicleResponse> Vehicles { get; set; }
}
This is the response JSON from the service:
{"results":[{"type":"MERCEDES BENZ - M (Svartur)","subType":"M","color":"Svartur","registryNumber":"GXS56","number":"GXS56","factoryNumber":"WDC1631131A539035","registeredAt":"23.09.2004","pollution":" g/km","weight":"2200 kg","status":"Í lagi","nextCheck":"01.06.2019"}]}
I am quite new to REST services so I believe that the problem is small....I am just not able to figure it out right now.
Your json has a root object that contains the list of your vehicles.
You need to name the variable that holds your list with the name returned in the json. results
public class VehicleResults
{
// This should be named results
public List<VehicleResponse> results {get;set;}
}
Now you can deserialize with
VehicleResults data = JsonConvert.DeserializeObject<VehicleResults>(json);
foreach(var vei in data.results)
Console.WriteLine(vei.type);
You need to [JsonProperty] on every property in VehicleResponse
Please add _reader.Close() at the end of the using
Related
I have this JSON data i'm receiving from my webservice, the problem now is that i'm currently trying to retrieve the data outside square bracket, because my current codes is only able to retrieve the weather data.
And whenever i try to get the data from coord it keeps returning me the value 0.
{
"coord":{
"lon":145.77,
"lat":-16.92
},
"weather":[
{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03n"
}
],
"base":"stations",
"main":{
"temp":300.15,
"pressure":1007,
"humidity":74,
"temp_min":300.15,
"temp_max":300.15
},
"visibility":10000,
"wind":{
"speed":3.6,
"deg":160
},
"clouds":{
"all":40
},
"dt":1485790200,
"sys":{
"type":1,
"id":8166,
"message":0.2064,
"country":"AU",
"sunrise":1485720272,
"sunset":1485766550
},
"id":2172797,
"name":"Cairns",
"cod":200
}
This is my current code i am trying to get the data from the curly bracket coord but it keeps giving 0. Any help would be appreciated thanks!
public partial class Book : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public class Result
{
public string id{ get; set; }
public string main{ get; set; }
public string description{ get; set; }
public string icon{ get; set; }
public decimal lon{ get; set; }
}
public class SearchList
{
public int resultCount;
public Result[] weather;
}
protected void Button1_Click(object sender, EventArgs e)
{
string searchTerm = TextBox1.Text;
var webRequest = (HttpWebRequest)WebRequest.Create
("http://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=b6907d289e10d714a6e88b30761fae22");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
JavaScriptSerializer json = new JavaScriptSerializer();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string resString = sr.ReadToEnd();
SearchList list = json.Deserialize<SearchList>(resString);
GridView1.DataSource = list.weather;
GridView1.DataBind();
}
else
Label1.Text = "Invalid Response";
}
}
Your models are incomplete. You can use
JsonCsharp to generate classes.
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class SearchList
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public int resultCount;
}
You need to add the model for coord
public class SearchList
{
public Coord coord;
public int resultCount;
public Result[] weather;
}
public class Coord
{
public double lon;
public double lat;
}
You will need to add more models for each type of data. You cannot simply access list.coord.lon from list.weather.lon
You were only able to retrieve the weather data because it was defined in the object model.
Update SearchList class definition to include the other desired data
public class SearchList {
public Position coord { get; set; }
public int resultCount { get; set; }
public Result[] weather { get; set; }
}
public class Position {
public double lon { get; set; }
public double lat { get; set; }
}
That way the JavaScriptSerializer will know to include it when deserializing the JSON.
use JObject then you can extract each Token using
`Jobject.SelectToken("datayouwant")`.
namespace ClassesRa.Classes
{
public class FicheLine
{
public int ItemRef { get; set; }
public double Amount { get; set; }
public string UnitCode { get; set; }
}
public class Fiche
{
public List<FicheLine> FicheLines { get; set; }
public Fiche()
{
FicheLines = new List<FicheLine>();
}
public string ClientCode { get; set; }
}
public class SalesFicheLine : FicheLine
{
public decimal Price { get; set; }
}
public class SalesFiche : Fiche
{
public List<SalesFicheLine> FicheLines { get; set; }
public SalesFiche()
{
FicheLines = new List<SalesFicheLine>();
}
public string PayCode { get; set; }
}
}
I want to derive SalesFiche from Fiche and add new members.
I want to derive SalesFicheLine from FicheLine and add new members.
I want to see SalesFicheLine in SalesFiche as FicheLine.
Is there a mistake or a defect in the above example?
namespace ClassesRa
{
public partial class fMain : Form
{
public fMain()
{
InitializeComponent();
}
private void fMain_Load(object sender, EventArgs e)
{
SalesFiche f = new SalesFiche();
f.ClientCode = "120.001";
f.PayCode = "30";
f.FicheLines.Add(new SalesFicheLine() { ItemRef = 1, Amount = 10, UnitCode = "PK", Price = 100 });
string xmlString = SerializeToString(f);
}
public string SerializeToString(object obj)
{
string str = "";
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
str = writer.ToString();
}
return str;
}
}
}
When I try to convert it to XML with the SerializeToString function, it gives the following error :
{"There was an error reflecting property 'FicheLines'."}
Thanks..
You have to rename the property "FicheLines" in your SalesFiche class. I tested it with "SalesFicheLines". This will fix the crash.
I also recommend that you change your SaleFiche class to this
public class SalesFiche : Fiche
{
public SalesFiche()
:base()
{
}
public string PayCode { get; set; }
}
You already have access to FicheLines's FicheLines property, so there's really no need to create another FicheLines property in SalesFiche.
i have j son data in string in j son response. I'm able to get only request-id value. other are coming in debugging but unable to retrieve from dictionary type.can u tell me how to get other values of a mobile number- date , status and description.
screen shot added kindly go through it http://postimg.org/image/6iad15yxl/
my j son data
{
"requestId": "546b384ce51f469a2e8b4567",
"numbers": {
"917566551111": {
"date": "2014-11-18 17:45:59",
"status": 1,
"desc": "DELIVERED"
}
}
}
C# code
public partial class jsontoCsharp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
json = Request.QueryString["data"];
var req = JsonConvert.DeserializeObject<Request>(json);
string requestid = req.requestId;
}
}
public class smsstatus
{
public string date { get; set; }
public int status { get; set; }
public string desc { get; set; }
}
public class Request
{
public string requestId { get; set; }
public Dictionary<string, smsstatus> numbers { get; set; } //<-- See this line
}
Your model should be something like this
public class smsstatus
{
public string date { get; set; }
public int status { get; set; }
public string desc { get; set; }
}
public class Request
{
public string requestId { get; set; }
public Dictionary<string, smsstatus> numbers { get; set; } //<-- See this line
}
Now these deserializations will work
var req = JsonConvert.DeserializeObject<Request>(json);
or
var req = new JavaScriptSerializer().Deserialize<Request>(json);
As your Json is quite complex, try as following..
var results = JsonConvert.DeserializeObject<dynamic>(json);
var result is containing your deserialized json now you can access the results object using dot (.) notation
{"balances-and-info":{"on_hold":[],"available": {"USD":0.93033384},"usd_volume":"243.18","fee_bracket": {"maker":"0.00","taker":"0.60"},"global_usd_volume":"0.09942900"}}
I have this JSON response, and I'm trying to store it in an object, however as you can see "balances-and-info" cannot be used as a variable name. The method I have been using is:
RestClient client = new RestClient("http://currency-api.appspot.com/api/");
RestRequest request = new RestRequest(url);
var response = client.Execute<Currency>(request);
Currency obj = response.Data;
Where obviously the class is a lot easier
public class Currency
{
public string rate { get; set; }
}
So how can I handle this?
String.replace() balances-and-info with balances_and_info
in your code
YourObject deserialized = parseResponse(obj.replace("balances-and-info", "balances_and_info"));
YourObject parseResponse(string response) {
try
{
// https://www.nuget.org/packages/Newtonsoft.Json/
// Json.NET
YourObject ret = JsonConvert.DeserializeObject<YourObject>(response);
return ret;
}
catch (JsonSerializationException)
{
// do something
}
return null;
}
YourObject
Use http://json2csharp.com/ and generate your object (copy response string, replace balances-and-info with balances_and_info and generate)
public class Available
{
public double USD { get; set; }
}
public class FeeBracket
{
public string maker { get; set; }
public string taker { get; set; }
}
public class BalancesAndInfo
{
public List<object> on_hold { get; set; }
public Available available { get; set; }
public string usd_volume { get; set; }
public FeeBracket fee_bracket { get; set; }
public string global_usd_volume { get; set; }
}
public class YourObject
{
public BalancesAndInfo balances_and_info { get; set; }
}
Im a little stuck and after some searching i turn to you:
class StatusResponse
{
protected int _statusCode { get; set; }
protected string _statusMessage { get; set; }
public StatusResponse(string Response)
{
if (!String.IsNullOrEmpty(Response))
{
this._statusCode = int.Parse((Response.Split(' '))[0].Trim());
this._statusMessage = Response;
}
}
}
class GroupStatusResponse : StatusResponse
{
public int Count { get; private set; }
public int FirstArticle { get; private set; }
public int LastArticle { get; private set; }
public string Newsgroup { get; private set; }
public GroupStatusResponse(string Response) : base(Response)
{
string[] splitResponse = Response.Split(' ');
this.Count = int.Parse(splitResponse[1].Trim());
this.FirstArticle = int.Parse(splitResponse[2].Trim());
this.LastArticle = int.Parse(splitResponse[3].Trim());
this.Newsgroup = splitResponse[4].Trim();
}
Why cant i do this:
GroupStatusResponse resp = new GroupStatusResponse("211 1234 3000234 3002322 misc.test");
Console.Writeline(resp._statusCode);
using
Console.Writeline(resp._statusCode);
from outside the derived class is public, and not protected use.
However, you could add something like:
class GroupStatusResponse : StatusResponse
{
public int GetStatusCode()
{
return _statusCode;
}
}
which is completely valid use.
Moreover, if the scenario is that _statusCode should be allowed to read by anyone, but only the base class should be able to set it, you could change its definition to:
public string _statusMessage { get; private set; }
It's because _statusCode is protected. This means the field is inaccessible outside of the class.