反序列化以下 JSON 時報錯:
[
{
"class": "Board",
"id": 1,
"articles": [{"class": "Article", "id": 1}],
"boardName": "122222",
"boarder": {"class": "User", "id": 1},
"description": "22222",
"postCount": 0
}
]
錯誤信息:Newtonsoft.Json.JsonConvert.DefaultSettings 未能計算表達式的值、emptyArray 相關字段不可用。
List articles 缺少泛型參數,應為 List<Article> articlesJsonSerializationException: Self referencing loop detectedboarder 對應 User 類,但 C# 類屬性名需一致或用 [JsonProperty] 標註public、屬性有 public getter/setterpublic class Board
{
[JsonProperty("class")]
public string Class { get; set; }
public int Id { get; set; }
[JsonProperty("articles")]
public List<Article> Articles { get; set; }
[JsonProperty("boardName")]
public string BoardName { get; set; }
[JsonProperty("boarder")]
public User Boarder { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("postCount")]
public int PostCount { get; set; }
}
public class Article
{
[JsonProperty("class")]
public string Class { get; set; }
public int Id { get; set; }
[JsonProperty("board")]
public Board Board { get; set; }
[JsonProperty("comments")]
public List<Comment> Comments { get; set; }
[JsonProperty("detail")]
public string Detail { get; set; }
[JsonProperty("lastReplyTime")]
public string LastReplyTime { get; set; }
[JsonProperty("owner")]
public User Owner { get; set; }
[JsonProperty("postTime")]
public string PostTime { get; set; }
[JsonProperty("replyCount")]
public int ReplyCount { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
}
public class User
{
[JsonProperty("class")]
public string Class { get; set; }
public int Id { get; set; }
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("articles")]
public List<Article> Articles { get; set; }
// ... 其他屬性
}
public class Comment
{
[JsonProperty("class")]
public string Class { get; set; }
public int Id { get; set; }
[JsonProperty("article")]
public Article Article { get; set; }
[JsonProperty("detail")]
public string Detail { get; set; }
[JsonProperty("owner")]
public User Owner { get; set; }
[JsonProperty("postTime")]
public string PostTime { get; set; }
}
var settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
List<Board> boards = JsonConvert.DeserializeObject<List<Board>>(json, settings);
JArray array = JArray.Parse(json);
foreach (JObject obj in array)
{
string boardName = obj["boardName"].ToString();
// 手動提取所需字段,避免實體類循環
}
Newtonsoft.Json.Silverlight.dll 而非標準版WebClient.DownloadStringAsync + 回調Deployment.Current.Dispatcher.BeginInvokeJToken.Parse(json) 驗證 JSON 結構JsonConvert.DeserializeObject<Board>(singleBoardJson)JsonConvert.SerializeObject(board, Formatting.Indented)核心修正:補全泛型參數、加上 JsonProperty 屬性、配置 ReferenceLoopHandling.Ignore。WP7 環境下優先考慮手動 JToken 解析以規避反射限制。