简体   繁体   English

Xamarin PCL C# - 将字符串反序列化为JSONObject / JSONArray

[英]Xamarin PCL C# - Deserialize string to a JSONObject/JSONArray

I've worked a lot with Android but today I have to work with Xamarin. 我在Android上做了很多工作,但今天我必须和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. 我正在创建一个PCL类,我正在尝试从字符串创建一个JSON对象( HttpWebResponse转换为字符串),以便从Android包装器调用。

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. 我从http响应中获取一个字符串,然后我想将其转换为JSON对象。 When the JSON object is created, I want to extract a value like in the example. 创建JSON对象时,我想提取一个类似示例的值。 However, I'm making it in a PCL, so is it possible to do this in Xamarin/C# from a PCL? 但是,我是用PCL制作的,所以可以在PCL中用Xamarin / C#做到这一点吗?

Thank for the help and reading! 感谢您的帮助和阅读!

You can deserialize the string into an object using Newtonsoft.Json library: 您可以使用Newtonsoft.Json库将字符串反序列化为对象:

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

You can also use HttpClient class instead of HttpWebRequest and automatically deserialize response into your object: 您还可以使用HttpClient类而不是HttpWebRequest并自动将响应反序列化到您的对象中:

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. 如果服务器在发生错误时返回不同的StatusCode,则可以使用HttpResponseMessage.IsSuccessStatusCode来决定将响应反序列化的类型。 If not you can use var jsonObject = JObject.Parse(jsonText); 如果没有,你可以使用var jsonObject = JObject.Parse(jsonText); and access the properties like this: jsonObject["someKey"] 并访问如下属性: jsonObject["someKey"]

You'll need Microsoft.AspNet.WebApi.Client library from Nuget 你需要Nuget的Microsoft.AspNet.WebApi.Client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM