4

I've worked a lot with Android but today I have to work with Xamarin. I'm making a PCL class and I'm trying to create a JSON object from a string (HttpWebResponse converted into a string) for calling from an Android wrapper.

After some research I wasn't able to find anything which really answers my question.

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

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

I get a string from http response and then I want to convert it into a JSON object. When the JSON object is created, I want to extract a value like in the example. However, I'm making it in a PCL, so is it possible to do this in Xamarin/C# from a PCL?

Thank for the help and reading!

1 Answer 1

5

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

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

You can also use HttpClient class instead of HttpWebRequest and automatically deserialize response into your object:

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

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

If you server returns different StatusCode when error happens you can use HttpResponseMessage.IsSuccessStatusCode to decide which type to deserialize the response into. If not you can use var jsonObject = JObject.Parse(jsonText); and access the properties like this: jsonObject["someKey"]

You'll need Microsoft.AspNet.WebApi.Client library from Nuget

Sign up to request clarification or add additional context in comments.

1 Comment

Thank for this fast answer ! I already saw that I can make it like you did, so maybe I didn't understand something. We are ok that I can, sometime, get an error response and then, it's not the same object as Account (if I take your code as example). So it can be either an Account object like or an Error object like? Do you understand what I mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.