Xamarin PCL C # - deserialize a string into JSONObject / JSONArray

I worked a lot with Android, but today I need to work with Xamarin. I am making a PCL class and I am trying to create a JSON object from a string ( HttpWebResponseconverted to a string) to be called from an Android wrapper.

After some research, I could not find anything that really answers my question.

Ultimately, I want to be able to just call something like this:

string value = jsonObject.get("key").getAsString();

I get the string from the HTTP response and then I want to convert it to a JSON object. When the JSON object is created, I want to extract the value, as in the example. However, I am doing this in PCL, so is it possible to do this in Xamarin / C # from PCL?

Thanks for the help and reading!

+4
source share
1 answer

You can deserialize a string into an object using Newtonsoft.Json :

Account account = JsonConvert.DeserializeObject<Account>(jsonFromServer);

You can also use the class HttpClientinstead HttpWebRequestand automatically deserialize the response into your object:

var client = new HttpClient();
var response = await client.GetAsync("/accounts");

Account account = await response.Content.ReadAsAsync<Account>();

If the server returns a different StatusCode when an error occurs, you can use HttpResponseMessage.IsSuccessStatusCodeto decide which type to deserialize the response. If not, you can use var jsonObject = JObject.Parse(jsonText);and access the following properties:jsonObject["someKey"]

You will need the Microsoft.AspNet.WebApi.Client library from Nuget

+5
source

All Articles