【发布时间】:2017-06-11 05:21:20
【问题描述】:
这是我第一次尝试 WCF/JSON。我创建了一个 WCF Web 服务。这是我的方法之一。这就是我将数据序列化为 JSON 的方式。
public string GetPrayers()
{
DataTable myDt = new DataTable();
myDt = sprocToDT("LoadPrayers");
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
return JSONString;
}
这会返回一个不错的 JSON 数据集:
{"GetPrayersResult":"[{\"prayerid\":2,\"prayer\":\"请为我祈祷 狗生锈。他得了癌症 :(\",\"prayerCategory\":\"General\",\"prayerDate\":\"2017-06-10T21:24:16.1\",\"句柄\":\"GuruJee\",\ "country\":\"USA\"},{\"prayerid\":1,\"prayer\":\"帮助 我需要阑尾切除术 STAT\",\"prayerCategory\":\"Sports\",\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"国家\":\"美国\"}]"}
当我去反序列化它时,我得到所有空值。这是我创建的类:
public class PrayUpPrayers
{
public string prayer { get; set; }
public string prayerid { get; set; }
public string prayerCategory { get; set; }
public string prayerCategoryID { get; set; }
public string prayerDate { get; set; }
public string handle { get; set; }
public string country { get; set; }
}
public class ThePrayer
{
public PrayUpPrayers prayers { get; set; }
}
}
这就是我检索 JSON 的方式:
void getData()
{
var request = HttpWebRequest.Create(string.Format(@"URLGoesHere"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
string foo = content.ToString();
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
测试总是空的?我序列化它的问题是错误的,可能是类结构,还是与我如何反序列化它有关。一个重要说明:我在其中一个 JSONClassesFromC# 站点上检查了我的 JSON,它只返回 GetPrayersResult 作为唯一的类项。完全忽略了我的整个结构。
【问题讨论】:
-
我想你差不多了,只是你需要反序列化 JSON 数组。例如 var a =
serializer.Deserialize<List<prayupapp.ModelClasses.PrayUpPrayers>>(foo) -
马上试试!
-
@turbot 什么是序列化程序。
-
当我使用这个时:
var a = serializer.Deserialize<List<prayupapp.ModelClasses.PrayUpPrayers>>(foo);我得到:序列化程序在这个上下文中不存在 -
抱歉,你应该使用
JsonConvert.DeserializeObjectList<prayupapp.ModelClasses.PrayUpPrayers>>(foo)
标签: c# json wcf serialization deserialization