【发布时间】:2016-02-04 11:31:29
【问题描述】:
我在将 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 返回字符串反序列化到我的 Object Newsletterlist 中, 但是在 JSON 字符串中,有一个 JSON 数组,我不知道如何将 JSON 数组反序列化为列表值。
JSON 字符串如下所示:
{
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”
}
【问题讨论】:
-
您需要知道数组中将返回给您的内容,如果它只是一个字符串值数组,则其值为
List<string>,如果它是一个复杂类型,则创建一个对象匹配它并有一个List<ComplexType> -
上述调用返回的字符串如下所示:"{\"success\":1,\"value\":[{\"id\":\"628461\", \"state\":\"draft\",\"html\":\"SOME-HTML-CODE\",\"name\":\"Neues Mailing\"}],\"status\":200 ,\"reason\":\"OK\"}" 我希望我能理解你的答案.. 所以我无法将该数组反序列化为类型 Newsletter[ ] 的数组,因为 Newsletter 类与数组 Response 匹配.
-
请参阅下面的答案以获得粗略的示例。只需更改 SomeType 以匹配您要返回的对象。
标签: c# arrays json serialization