c# .net反序列化JSON
本文关键字:JSON 反序列化 net | 更新日期: 2023-09-27 18:15:37
我试图在我的对象中反序列化JSON:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class FormData
{
public string audience { get; set; }
public Calendar[] calendar { get; set; }
public FormData()
{
//
// TODO: Add constructor logic here
//
}
public class Calendar
{
public Quarter quarter { get; set; }
}
public class Quarter
{
public int qtrNumber { get; set; }
public string qtrString { get; set; }
public int[] qtrTools { get; set; }
public int qtrYear { get; set; }
}
}
这是我的处理器:
<%@ WebHandler Language="C#" Class="ToolHandler" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
using System.Text;
using System.IO;
public class ToolHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.ContentType = "text/plain";
try
{
string strJson = new StreamReader(Request.InputStream).ReadToEnd();
//deserialize the object
FormData formData = serializer.Deserialize<FormData>(strJson);
if (formData != null)
{
Response.Write("Success!!");
}
else
{
Response.Write("No Data");
}
}
catch (Exception ex)
{
Response.Write("Error :" + ex.Message);
}
}
public bool IsReusable {
get {
return false;
}
}
}
JSON: {
"audience": "8",
"calendar": [
{
"qtrNumber": 1,
"qtrYear": 2016,
"qtrString": "1st Quarter",
"qtrTools": [
"3",
"4"
]
},
{
"qtrNumber": 2,
"qtrYear": 2016,
"qtrString": "2nd Quarter",
"qtrTools": []
},
{
"qtrNumber": 3,
"qtrYear": 2016,
"qtrString": "3rd Quarter",
"qtrTools": []
},
{
"qtrNumber": 4,
"qtrYear": 2016,
"qtrString": "4th Quarter",
"qtrTools": []
}
]
}
执行完这行后我看到的:
FormData formData = serializer.Deserialize<FormData>(strJson);
formData对象有适当的受众和日历与4个元素的数组,但所有日历[]。四分之一对象为空。
Calendar
类在JSON中没有嵌套Quarter
属性。你可以"unnest"嵌套的属性,一切都应该正常工作:
public class FormData
{
public string audience { get; set; }
public Calendar[] calendar { get; set; }
public FormData()
{
//
// TODO: Add constructor logic here
//
}
public class Calendar
{
public int qtrNumber { get; set; }
public string qtrString { get; set; }
public int[] qtrTools { get; set; }
public int qtrYear { get; set; }
}
}
示例:https://dotnetfiddle.net/mq1wyP
没有"qtr"属性在calendar
上,它们在Quarter
上。JSON必须是:
{
"audience": "8",
"calendar": [ {"Quarter" :
{
"qtrNumber": 1,
"qtrYear": 2016,
"qtrString": "1st Quarter",
"qtrTools": [
"3",
"4"
]
}},
{"Quarter" : {
"qtrNumber": 2,
"qtrYear": 2016,
"qtrString": "2nd Quarter",
"qtrTools": []
}},
etc...
]
}