我有以下代码:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent中的输入是JSON,但它没有正确地反序列化为对象。我应该如何正确地反序列化它?
我有以下代码:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent中的输入是JSON,但它没有正确地反序列化为对象。我应该如何正确地反序列化它?
当前回答
以下来自msdn站点的内容应该有助于为您正在寻找的内容提供一些本地功能。请注意,这是针对Windows 8指定的。下面列出了该站点中的一个这样的示例。
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
它利用了Windows.Data.JSON命名空间。
其他回答
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
DataContractJsonSerializer(typeof(UserListing));
UserListing response = (UserListing)deserializer.ReadObject(ms);
}
public class UserListing
{
public List<UserList> users { get; set; }
}
public class UserList
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
试试下面的代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
JObject joResponse = JObject.Parse(objText);
JObject result = (JObject)joResponse["result"];
array = (JArray)result["Detail"];
string statu = array[0]["dlrStat"].ToString();
}
string json = @"{
'Name': 'Wide Web',
'Url': 'www.wideweb.com.br'}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic j = jsonSerializer.Deserialize<dynamic>(json);
string name = j["Name"].ToString();
string url = j["Url"].ToString();
我假设你没有使用Json。净(Newtonsoft。Json NuGet包)。如果是这样的话,你应该试试。
它具有以下特点:
LINQ到JSON JsonSerializer用于快速将.NET对象转换为JSON并再转换回来 Json。NET可以选择生成格式良好、缩进的JSON以供调试或显示 可以将JsonIgnore和JsonProperty等属性添加到类中,以自定义类的序列化方式 能够将JSON转换为XML 支持多种平台:.NET、Silverlight和Compact Framework
请看下面的例子。在本例中,JsonConvert类用于将对象与JSON进行转换。它有两个用于此目的的静态方法。它们是SerializeObject(Object obj)和DeserializeObject<T>(String json):
using Newtonsoft.Json;
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
下面是一个使用csc v2.0.0.61501的完整的可运行示例。
包:
nuget install Microsoft.AspNet.WebApi.Core
nuget install Microsoft.Net.Http
nuget install Newtonsoft.Json
代码:
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
public static class App
{
static void Main()
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
string url = "https://httpbin.org/get";
var client = new HttpClient();
// The verbose way:
//HttpResponseMessage response = await client.GetAsync(url);
//response.EnsureSuccessStatusCode();
//string responseBody = await response.Content.ReadAsStringAsync();
// Or:
string responseBody = await client.GetStringAsync(url);
var obj = JsonConvert.DeserializeObject<dynamic>(responseBody);
Console.WriteLine(obj);
Console.WriteLine(obj.headers.Host);
}
}
编译器命令:
csc http_request2.cs -r:".\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll" -r:".\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll" -r:".\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll"
输出:
{
"args": {},
"headers": {
"Host": "httpbin.org",
"X-Amzn-Trace-Id": "Root=1-633dce52-64f923bb42c99bf46f78672c"
},
"origin": "98.51.7.199",
"url": "https://httpbin.org/get"
}
httpbin.org
无法加载Newtonsoft.json文件或程序集。系统无法找到指定的文件,我不得不将Newtonsoft.Json.dll移到已编译的二进制文件旁边。