Parsing data from json in C# - c#

I successfully got data to var content
The code how I did it:
public async void FetchAsync()
{
var client = new RestClient("http://api.locopal.com");
var request = new RestRequest("/countries", Method.POST);
var response = client.Execute(request);
var content = response.Content;
var responseCountries = JArray.Parse(JObject.Parse(content)[""].ToString());
}
But in line: var responseCountries = JArray.Parse(JObject.Parse(content)[""].ToString()); I got An unhandled exception occured.
This is the data from var content:
Countries from here need to be write down to list.

You could declare a class like the following
public class Country
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("nicename")]
public string Name { get; set; }
}
and then deserialize the json as below:
var responseCountries = JsonConvert.DeserializeObject<IEnumerable<Country>>(content);

You should deserialize the JSON into an object. You can create a POCO object with the properties from the JSON.
Example:
public class Country
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("nicename")]
public string Name { get; set; }
}
Edit: Follow same casing as in JSON

Related

Unable to use JSON array for Azure Function

I have below JSON input for My azure function but unable to pass it in after deserialize object
{
"name": [{
"SiteName": "Site1",
"SiteUrl": "https://site1.com/"
},
{
"SiteName": "Site2",
"SiteUrl": "https://site2.com/"
},
]
}
after deserialize I am getting count as 2 but inside array value I am not getting for deserializing using below code
string requestBody = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
var Root = data["name"].ToObject<List<Constant>>();
and for Constant class declared like below
class Constant
{
public Dictionary<string, string> name { get; set; }
}
Try to create class like below.
class JsonResponse
{
public List<Constant> name { get; set; }
}
class Constant
{
public string SiteName { get; set; }
public string SiteUrl { get; set; }
}
And try to Deserialize response with JsonConvert.DeserializeObject<JsonResponse>(requestBody).
string requestBody = new StreamReader(req.Body).ReadToEnd();
JsonResponse data = JsonConvert.DeserializeObject<JsonResponse>(requestBody);
var Root = data.name;
Solution 1: Deserialize as object list
The model class should be:
public class Site
{
public string SiteName { get; set; }
public string SiteUrl { get; set; }
}
And deserialize as below:
var Root = data["name"].ToObject<List<Site>>();
Sample program (Site class)
Solution 2: Deserialize as Dictionary
var Root = data["name"].ToObject<List<Dictionary<string, string>>>();
Sample program (Dictionary)

Can't return my result in async method

In an MVVM pattern I'm trying to make an async method that fetches a json string, and returns the result as a List<Cabinet> so that I can use this list later.
I have json that looks like this, it represents a list of cabinet object:
{"cabinets":[{"id":"1","longitudeGPS":"2,2891506","latitudeGPS":"48,8618687","cp":"75016","ville":"Paris","rue":"1 Avenue Gustave V de Su\u00e8de"},{"id":"2","longitudeGPS":"3,0566481","latitudeGPS":"50,6302592","cp":"59800","ville":"Lille","rue":"127 Rue Solf\u00e9rino"},{"id":"3","longitudeGPS":"3,8749271","latitudeGPS":"43,6110374","cp":"34000","ville":"Montpellier","rue":"17 Rue Foch"},{"id":"4","longitudeGPS":"-1,6736931","latitudeGPS":"48,1181043","cp":"35700","ville":"Rennes","rue":"127 23 Rue de Vincennes"},{"id":"5","longitudeGPS":"0,0991065","latitudeGPS":"49,4931952","cp":"76600","ville":"Le Havre","rue":"32 Avenue Foch"},{"id":"6","longitudeGPS":"4,8353320","latitudeGPS":"45,7639021","cp":"69002","ville":"Lyon","rue":"27 Rue Henri Germain"}]}
I've created the classes according to json2csharp generator:
public class Cabinet
{
public string id { get; set; }
public string longitudeGPS { get; set; }
public string latitudeGPS { get; set; }
public string cp { get; set; }
public string ville { get; set; }
public string rue { get; set; }
}
public class CabinetList
{
public List<Cabinet> cabinets { get; set; }
}
Here I have an HttpClient that fetches the json from the website and stores it in a listCabinet variable.
public string adresseCabinets = "http://ppe3JoJuAd/gsbAppliFraisV2/webservices/w_cabinet.php";
public static string userId;
CabinetsList listeCabinets = new CabinetsList();
public async Task<List<CabinetsList>>loadCabinets()
{
HttpClient clientCabinets = new HttpClient();
var response = await clientCabinets.GetAsync(adresseCabinets);
var json = response.Content.ReadAsStringAsync().Result;
listeCabinets = JsonConvert.DeserializeObject<CabinetsList>(json);
}
When I want to return the listeCabinets variable I have the following error: cannot implicitly convert type cabinetList to System.Collection.Generic.List CabinetList
How can I solve this?
The return type of your method is List<CabinetsList>, while the output of DeserializeObject<CabinetsList> is a CabinetsList. You should deserialize the JSON as the type you want to return:
return JsonConvert.DeserializeObject<List<CabinetsList>>(json);
Or create a new list to add the one and only cabinet to if the JSON contains just one:
return new List<CabinetsList> { JsonConvert.DeserializeObject<CabinetsList>(json) };
Side note: and of course await the result:
var json = await response.Content.ReadAsStringAsync();

How to convert HttpResponseMessage having OData to a C# object?

I am calling a REST service from my C# application which connects to CRM.
This returns HttpResponseMessage.
response.Content.ReadAsStringAsync().Result
The above statement returns following output. I need to convert this to Account object, which already has "accountnumber, and accountid properties.
{
"#odata.context":"https://APIURL/api/data/v8.1/$metadata#account(accountnumber)","value":[
{
"#odata.etag":"W/\"12496866\"","accountnumber":"D00208","accountid":"30417c0f-7b8c-e611-80f3-5065f38bd4d1"
} ] }
I have tried following code
Account return = JsonConvert.DeserializeObject<Account>(response.Content.ReadAsStringAsync().Result);
But this doesn't fill up the object, and it always has null values in accountnumber, and accountid fields.
Any idea of how to properly convert this response to the C# type.
you should do it like this -
public class Value
{
[JsonProperty("#odata.etag")]
public string etag { get; set; }
public string accountnumber { get; set; }
public string accountid { get; set; }
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string context { get; set; }
public List<Value> value { get; set; }
}
then deserialize-
var value = JsonConvert.DeserializeObject<RootObject>(json);
We can parse and create Anonymous Type based on that. In your case, replace the Anonymous Type with Account object.
Given the JSON string:
string json = #"{
'#odata.context':'https://APIURL/api/data/v8.1/$metadata#account(accountnumber)',
'value':[
{
'#odata.etag':'W/\'12496866\'',
'accountnumber':'D00208',
'accountid':'30417c0f-7b8c-e611-80f3-5065f38bd4d1'
}
]
}";
It can be parsed as below:
var jsonObject = JObject.Parse(json);
var dataObject = new
{
Context = jsonObject["#odata.context"],
Values = jsonObject["value"].AsEnumerable<JToken>()
.Select(v => new
{
ETag = v["#odata.etag"],
AccountNumber = v["accountnumber"],
AccountId = v["accountid"]
}).ToArray()
};
In order to convert to Account object where the object is defined as below:
public class Account
{
public string Number { get; set; }
public string Id { get; set; }
}
Then the JSON object can be parsed as below (if looking for only first node; It can also be converted to list of Accounts:
var jsonObject = JObject.Parse(json);
var account = jsonObject["value"].AsEnumerable<JToken>()
.Select(v => new Account()
{
Number = v["accountnumber"].ToString(),
Id = v["accountid"].ToString()
}).FirstOrDefault();
You can generalize the accepted answer by using a generic class to deserialize json web response:
class RootObject<T>
{
public List<T> Value { get; set; }
}
var odata = JsonConvert.DeserializeObject<RootObject<POCO>>(json);
Try it with live Demo

Json RestSharp deserilizing Response Data null

i use RestSharp to access a Rest API. I like to get Data back as an POCO.
My RestSharp Client looks like this:
var client = new RestClient(#"http:\\localhost:8080");
var request = new RestRequest("todos/{id}", Method.GET);
request.AddUrlSegment("id", "4");
//request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
//With enabling the next line I get an new empty object of TODO
//as Data
//client.AddHandler("*", new JsonDeserializer());
IRestResponse<ToDo> response2 = client.Execute<ToDo>(request);
ToDo td=new JsonDeserializer().Deserialize<ToDo>(response2);
var name = response2.Data.name;
my Class for the JsonObject looks like this:
public class ToDo
{
public int id;
public string created_at;
public string updated_at;
public string name;
}
and the Json Response:
{
"id":4,
"created_at":"2015-06-18 09:43:15",
"updated_at":"2015-06-18 09:43:15",
"name":"Another Random Test"
}
Per the documentation, RestSharp only deserializes to properties and you're using fields.
RestSharp uses your class as the starting point, looping through each
publicly-accessible, writable property and searching for a
corresponding element in the data returned.
You need to change your ToDo class to the following:
public class ToDo
{
public int id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string name { get; set; }
}

Metro App - deserialize JSON String

I'd like to deserialize a JSON string which I get from a webservice. My problem is, that the deserialized object class array (of type Result) has always 0 items in it....
But the webservice returns the correct string.
So I think the failure occurs in the way how I deserialize the string/stream.
Any ideas what's my fault?
//JSON result string:
{"Results":
[{"Result":{
"Name":"Rechnung2",
"Date1":"2012-10-05",
"Item1":"50",
"Item2":"10",
"CompanyName":"Contoso",
"Description":"My description"}}]
}
[DataContract]
public class Result
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Date1 { get; set; }
[DataMember]
public string Item1 { get; set; }
[DataMember]
public string Item2 { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string Description { get; set; }
}
public async void GetjsonStream()
{
HttpClient client = new HttpClient();
string url = "http://localhost/test/api.php?format=json&key=12345";
HttpResponseMessage response = await client.GetAsync(url);
//ReadAsStringAsync() works fine, so I think ReadAsStreamAsync() works also fine
var str = await response.Content.ReadAsStreamAsync();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Result[]));
//Result has always 0 items
Result[] res = (Result[])ser.ReadObject(str);
}
I haven't used DataContractJsonSerializer myself, so this may not be the best approach - but I suspect that the problem is that the JSON represents "an object containing a collection of results" - not "a collection of results".
Try this, in addition to your existing code:
[DataContract]
public class ResultCollection
{
[DataMember]
public Result[] Results { get; set; }
}
...
var ser = new DataContractJsonSerializer(typeof(ResultCollection));
var collection = (ResultCollection)ser.ReadObject(str);
var results = collection.Results;
You may be able to change the type of Results to List<Result> too, if that's helpful.
(I've just tried the code above, and it gave me the right result, so it looks like this is at least along the right lines...)

Categories