我想用c#在asp.net中解析这个json数组 这是要解析的示例Json数据:
[
{
"idvisit":"3",
"iduser":"shoaibshakeel",
"idpage":"1",
"pagetime":"0"
},
{
"idvisit":"4",
"iduser":"shoaibshakeel",
"idpage":"2",
"pagetime":"28"
},
{
"idvisit":"5",
"iduser":"shoaibshakeel",
"idpage":"3",
"pagetime":"0"
}
]
这是我目前在我的代码文件中执行的操作:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string jsonData = Request.Form[0];
Response.Write(jsonData);
Response.Write("<br/>");
PiwikDbData[] visitlist;
//deserialize json array
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(PiwikDbData));
visitlist = serializer.ReadObject(stream) as PiwikDbData[];
}
Response.Write(visitlist.Length);
}
}
[DataContract]
class PiwikDbData
{
[DataMember(Name = "idvisit", IsRequired = true)]
public int idvisit;
[DataMember(Name = "iduser", IsRequired = true)]
public string iduser;
[DataMember(Name = "idpage", IsRequired = true)]
public int idpage;
[DataMember(Name = "pagetime", IsRequired = true)]
public int pageTime;
}
我在这里做错了什么。在visitlist = serializer.ReadObject(stream) as PiwikDbData[];
显示“根级别的数据无效”
非常感谢帮助。感谢。
答案 0 :(得分:3)
您正在使用为XML-Data制作的DataContractSerializer。
http://msdn.microsoft.com/de-de/library/system.runtime.serialization.datacontractserializer(v=vs.100).aspx
对于JSON-Data,您应该使用DataContractJsonSerializer:
http://msdn.microsoft.com/de-de/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
您还尝试反序列化单个项目
new DataContractSerializer(typeof(PiwikDbData));
但你真正需要的是一系列物品
new DataContractSerializer(typeof(PiwikDbData[]));
这就是我的代码如何:
string jsonData = Request.Form[0];
Response.Write(jsonData);
Response.Write("<br/>");
PiwikDbData[] visitlist;
//deserialize json array
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(PiwikDbData[]));
visitlist = (PiwikDbData[])serializer.ReadObject(stream);
}
Response.Write(visitlist.Length);
答案 1 :(得分:3)
只需下载JSON.NET,然后使用:
var wikiData = JsonConvert.DeserializeObject<List<PiwikDbData>>(jsonData);
这应该返回一个JArray对象,它将是List类型。
答案 2 :(得分:0)
您尝试使用一个item元素解析json数组结果。
我认为正确的路线是:
...
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(List<PiwikDbData>));
List<PiwikDbData>visitlist = serializer.ReadObject(stream);
}
...
答案 3 :(得分:0)
使用以下代码:
//deserialize json array
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData)))
{
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(PiwikDbData[]));
visitlist = serializer.ReadObject(stream) as PiwikDbData[];
}
Response.Write(visitlist.Length);