all values not coming while parsing json to string in c# - c#

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

Related

deserialize API response with different json value in the result

I'm querying an external service and wanted to deserialize the response into a customer object but the issue is response for each customer may be different. some customer may have Sales entity in the response and few may have Marketing.
The json property for sales entity is SalesId and for marketing is MarketingId. Can you advise whether the model I use to store result is correct or any improvement ? If so, how would I deserialize the response without knowing the correct json property ?
For Customer 66666
{
"customerId": "66666",
"customerName": "test1234",
"dependentEntity": [
{
"SalesId": "3433434",
"SalesPersonName": "343434",
"SaleSource": "StorePurchase"
}
]
}
For Customer 5555
{
"customerId": "55555",
"customerName": "test2",
"dependentEntity": [
{
"MarketingId": "3433434",
"MarketingAppName": "343434",
"MarketingSource": "Online"
}
]
}
Here is the Model I'm thinking but not sure the correct one
public class Customer
{
public string customerId { get; set; }
public string customerName { get; set; }
public IList<T> dependentList { get; set; }
}
public class Dependent
{
[JsonProperty("Id")]
public string Id { get; set; }
public string Name { get; set; }
public string Source { get; set; }
}
You could probably try something like the following one:
public class DependentEntity
{
[JsonProperty("SalesId")]
public string SalesId { get; set; }
[JsonProperty("SalesPersonName")]
public string SalesPersonName { get; set; }
[JsonProperty("SaleSource")]
public string SaleSource { get; set; }
[JsonProperty("MarketingId")]
public string MarketingId { get; set; }
[JsonProperty("MarketingAppName")]
public string MarketingAppName { get; set; }
[JsonProperty("MarketingSource")]
public string MarketingSource { get; set; }
}
public class Customer
{
[JsonProperty("customerId")]
public string CustomerId { get; set; }
[JsonProperty("customerName")]
public string CustomerName { get; set; }
[JsonProperty("dependentEntity")]
public IList<DependentEntity> DependentEntity { get; set; }
}
We have a type for DependentEntity that has both the attributes of Marketing and Sales object. After parsing your input, you could create a logic (checking the attributes) based on which you could check if a DependentEntity is a Marketing or a Sales object.
The above classes was generated using, jsonutils.
If we can assume that the dependentEntity contains only a single type of objects then you can use json.net's schema to perform branching based on the matching schema.
So, lets suppose you have these dependent entity definitions:
public class DependentMarket
{
public string MarketingId { get; set; }
public string MarketingAppName { get; set; }
public string MarketingSource { get; set; }
}
public class DependentSales
{
public string SalesId { get; set; }
public string SalesPersonName { get; set; }
[JsonProperty("SaleSource")]
public string SalesSource { get; set; }
}
...
Then you can use these classes to generate json schemas dynamically:
private static JSchema marketSchema;
private static JSchema salesSchema;
//...
var generator = new JSchemaGenerator();
marketSchema = generator.Generate(typeof(DependentMarket));
salesSchema = generator.Generate(typeof(DependentSales));
And finally you can do the branching like this:
var json = "...";
var semiParsedJson = JObject.Parse(json);
JArray dependentEntities = (JArray)semiParsedJson["dependentEntity"];
JObject probeEntity = (JObject)dependentEntities.First();
if (probeEntity.IsValid(marketSchema))
{
var marketEntities = dependentEntities.ToObject<List<DependentMarket>>();
...
}
else if (probeEntity.IsValid(salesSchema))
{
var salesEntities = dependentEntities.ToObject<List<DependentSales>>();
...
}
else if ...
else
{
throw new NotSupportedException("The provided json format is not supported");
}

JsonConvert.DeserializeObject not working in .net

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

C# Entity Framework Json deserialize String array issues

I have A Json file Which can be used for deserialize to Entity framework. For simplify we can assume the Json like this
{
"stat": "val0",
"results": [
{
"datasets": [
"val1",
"val2"
],
"head": "val3"
},
{
"datasets": [
"val4",
"val5"
],
"head": "val6"
}
]
}
And my Entity Classes like
[Serializable]
public class Root
{
[Key]
public int Id { get; set; }
public int stat { get; set; }
public List<Result> results { get; set; }
}
[Serializable]
public class Result
{
[Key]
public int Id { get; set; }
public List<String> _strings { get; set; }
public List<string> Strings
{
get { return _strings; }
set { _strings = value; }
}
[Required]
public string datasets
{
get { return String.Join(",", _strings); }
set { _strings = value.Split(',').ToList(); }
}
public string head{ get; set; }
public virtual root { get; set; }
}
I know Entity Framework does not support primitive types and I know problem causes from my datasets fields. that I found this way to solve String array deserialize issue here. I have tried
URL = "http://...";//Restful webservice address
WebClient client = new WebClient();
String JSON= client.DownloadString(URL);
var dsobj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(json);
But I got
System.InvalidOperationException
Then I have decided to use Newtonsoft
URL = "http://...";//Restful webservice address
WebClient client = new WebClient();
String JSON= client.DownloadString(URL);
var dsobj = JsonConvert.DeserializeObject<Root>(json);
Then I got this error
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path 'results[0].senses[0].definition', line 1, position...
I found this but I cant figure it out.
How can Fix these isseus. Any help appreciated.
Your json consist of two unwanted commas, try removing those
try
[Serializable]
public class Root
{
[Key]
public int Id { get; set; }
public string stat { get; set; } // changed to a string
public List<Result> results { get; set; }
}
[Serializable]
public class Result
{
[Key]
public int Id { get; set; }
public List<String> _dataSets { get; set; }
public List<string> dataSets // the JSON array will deserialize into this property
{
get { return _dataSets; }
set { _dataSets = value; }
}
[Required]
public string DatasetsAsString
{
get { return String.Join(",", _dataSets); }
set { _dataSets = value.Split(',').ToList(); }
}
public string head{ get; set; }
public virtual root { get; set; }
}
Edit: stat property has to be a string too.

C# How to get data from JSON

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")`.

Xamarin.Forms WebAPI JsonConverter.DeserializeObject unhandled exception

I'm trying to replicate the functionality in one of MoshHamedani's course on Xamarin Forms.
Here's my code (with a valid, working _url, that returns a json object with escape characters):
public partial class PartnersListPage : ContentPage
{
private const string _url = "xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz";
private HttpClient _httpClient = new HttpClient();
private ObservableCollection<Partner> _partners;
public PartnersListPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
var jsonObject = await _httpClient.GetStringAsync(_url);
var dotNetObject = JsonConvert.DeserializeObject<List<Partner>>(jsonObject);
_partners = new ObservableCollection<Partner>(dotNetObject);
partnersListView.ItemsSource = _partners;
base.OnAppearing();
}
Partner.cs looks like this:
public class Partner
{
//public int Id { get; set; }
//public string Name { get; set; }
public string ImageUrl { get; set; }
public string WebUrl { get; set; }
}
Postman returns the following:
{
"partners": [
{
"imageUrl": "http://www.abcdefgh.xy//media/1007/3.jpg",
"webUrl": "http://www.abcdefgh.xy/"
},
{
"imageUrl": "http://www.ijklmnop.xy//media/1009/5.jpg",
"webUrl": "https://www.ijklmnop.xy/xy"
},
{
"imageUrl": "http://www.qrstuvxy.xy//media/2623/slsp.svg",
"webUrl": "https://www.qrstuvxy.xy/"
}
]
}
When I hit the JsonConvert.DeserializeObject line, I get the following:
An unhandled exception occured. Why is it not working?
You are deserializing with incorrect type (List<Partner>)
I'm using Json to c# converter in order to determine the class I need - just paste in your json text/data and in will generate the classes for you. For the example for your json text/data you need:
public class Partner
{
public string imageUrl { get; set; }
public string webUrl { get; set; }
}
public class RootObject
{
public List<Partner> partners { get; set; }
}
........
var result = JsonConvert.DeserializeObject<RootObject>(jsonObject);
controller returning single object but you are trying to array deserialize
public class Partner
{
//public int Id { get; set; }
//public string Name { get; set; }
public string ImageUrl { get; set; }
public string WebUrl { get; set; }
}
public class ApiResult
{
List<Partner> Partners {get;set;}
}
and..
var dotNetObject = JsonConvert.DeserializeObject<ApiResult>(jsonObject);

Categories

Resources