我无法将JSON字符串反序列化为我写的类。
这是我的课程
class Newsletter
{
public string id;
public string state;
public string html;
public string name;
}
class ApiReply
{
int success;
//string value;
int status;
string reason;
}
class Newsletterlist : ApiReply
{
private const string URL = "https://www.newsletter2go.de/de/api/get/newsletters/";
public string key { private set; get; }
public Newsletterlist()
{
key = "MYAPIKEY";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
byte[] data = PostData.get_postData(this);
httpWebRequest.ContentLength = data.Length;
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic temp = JsonConvert.DeserializeObject(responseString);
}
public List<Newsletter> value {private set;get;}
}
我想将JSON返回字符串反序列化为我的对象新闻稿列表, 但是在JSON字符串中,有一个JSON数组,我不知道如何将JSON数组反序列化为List Value。
JSON String看起来像这样:
{
success : 0,
value : [], <-- Value may contain a JSON Array wich I want to Serialize to List<Newsletter>
status :405,
reason : “Method Not Allowed , POST Required”
}
答案 0 :(得分:2)
你需要知道在数组中将返回给你的是什么,如果它只是一个字符串值数组,那么如果它是一个复杂类型则值为List<string>
然后创建一个匹配它的对象有一个List<ComplexType>
class ApiReply
{
int success {get;set}
List<string> value {get;set;}
int status {get;set;}
string reason {get;set;}
}
或复杂类型:
public class SomeType
{
public string Name {get;set;}
public int Age {get;set;}
}
class ApiReply
{
int success {get;set}
List<SomeType> value {get;set;}
int status {get;set;}
string reason {get;set;}
}
这样的JSON看起来像这样:
{
success : 0,
value : [{name="fred", age=21},{name="paul", age=53}], <-- Value may contain a JSON Array
status :405,
reason : “Method Not Allowed , POST Required”
}
复杂子数组的示例:JSONConvert.DeserializeObject not handling child array with unnamed array items