我有一个以下有效的json字符串:
var result = "[{\"total\":" + wpTotal + ",\"totalpages\":" + wpTotalPages + "},{\"tags\":[{\"id\":384},{\"id\":385}]}]";
我正在尝试使用此方法将其反序列化为类型为T的对象:
public static T FromJSON<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var settings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
};
var serializer = new DataContractJsonSerializer(typeof(T), settings);
return (T)serializer.ReadObject(ms);
}
}
并像这样使用它:
var obj = JsonHelper.FromJSON<TagsResponse>(result);
我总是得到空结果(null),没有任何异常或任何类型的信息。
我的模特是:
[DataContract]
public class TagsResponse
{
[DataMember(Name = "total")]
public int Total { get; set; }
[DataMember(Name = "totalpages")]
public int TotalPages { get; set; }
[DataMember(Name = "tags")]
public List<Tag> Tags { get; set; }
}
问题出在哪里?
答案 0 :(得分:1)
输入格式有问题,json字符串中的属性不是对象的预期级别,这是一个有效的例子:
class Program
{
static void Main(string[] args)
{
var json = "{\"total\":" + 1 + ",\"totalpages\":" + 10 + ",\"tags\":[{\"id\":384},{\"id\":385}]}";
var result = json.FromJSON<TagsResponse>();
Console.WriteLine("Hello World!" + result);
}
}
public static class Helper
{
public static T FromJSON<T>(this string json)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)serializer.ReadObject(ms);
}
}
}
[DataContract]
public class TagsResponse
{
[DataMember(Name = "total")]
public int Total { get; set; }
[DataMember(Name = "totalpages")]
public int TotalPages { get; set; }
[DataMember(Name = "tags")]
public List<Tag> Tags { get; set; }
}
[DataContract]
public class Tag
{
[DataMember(Name = "id")]
public string Id { get; set; }
}
答案 1 :(得分:1)
1)创建正确的json
var result = "[{\"total\":" + wpTotal + ",\"totalpages\":" + wpTotalPages + ",\"tags\":[{\"id\":384},{\"id\":385}]}]";
2)将其解析为数组
var obj = JsonHelper.FromJSON<TagsResponse[]>(result);
或,如果要将其解析为单个项目,可以从json中删除[]
var result = "{\"total\":" + wpTotal + ",\"totalpages\":" + wpTotalPages + ",\"tags\":[{\"id\":384},{\"id\":385}]}";
var obj = JsonHelper.FromJSON<TagsResponse>(result);