本文介绍了C#JSON.NET类型无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我将JSON字符串转换为C#类时,我已经看到了类名只包含数字。
如何反序列化JSON字符串?
public class 904 { public string id {get;组; } public string name {get;组; } public string name_url {get;组; } public string region_path {get;组; } } public class Result { public 904 904 {get;组; } } public class RootObject { public bool status {get;组; } public Result result {get;组; } public int time_valid_to {get;组; } }JSON字符串
{status:true,result:{904:{id:904,name:Wien Alsergrund,name_url: wien_alsergrund,region_path:oesterreich\ / wien\ / wien_alsergrund}},time_valid_to:1424978715}解决方案
看起来像 result 属性实际上是一个结果映射, 字典<,> 。这工作:
使用System; using System.Collections.Generic; using System.IO; using System.Linq; 使用Newtonsoft.Json; public class ResultEntry { public string id {get;组; } public string name {get;组; } public string name_url {get;}组; } public string region_path {get;组; } } public class RootObject { public bool status {get;组; } public Dictionary< int,ResultEntry> result {get;组; } public int time_valid_to {get;组; } } class Test { static void Main() { string json = File.ReadAllText(json.txt ); var root = JsonConvert.DeserializeObject< RootObject>(json); Console.WriteLine(root.result [904] .name); } }我强烈建议使用更清晰的属性名称属性告诉Json.NET如何将它们映射到JSON。
I am curenntly making an thunder storm app for windows phone but i have a problem.
When i have converted the JSON string to C# classes i have seen that the class names just contain numbers.
How can i deserialize the JSON String?
public class 904 { public string id { get; set; } public string name { get; set; } public string name_url { get; set; } public string region_path { get; set; } } public class Result { public 904 904 { get; set; } } public class RootObject { public bool status { get; set; } public Result result { get; set; } public int time_valid_to { get; set; } }The JSON string
{"status":true,"result":{"904":{"id":"904","name":"Wien Alsergrund","name_url":"wien_alsergrund","region_path":"oesterreich\/wien\/wien_alsergrund"}},"time_valid_to":1424978715}解决方案
It looks like the result property is effectively a map of results - so you can represent that with a Dictionary<,>. This works:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; public class ResultEntry { public string id { get; set; } public string name { get; set; } public string name_url { get; set; } public string region_path { get; set; } } public class RootObject { public bool status { get; set; } public Dictionary<int, ResultEntry> result { get; set; } public int time_valid_to { get; set; } } class Test { static void Main() { string json = File.ReadAllText("json.txt"); var root = JsonConvert.DeserializeObject<RootObject>(json); Console.WriteLine(root.result[904].name); } }I'd strongly recommend using cleaner property names and specifying attributes to tell Json.NET how to map them to JSON though.
更多推荐
C#JSON.NET类型无效
发布评论