尝试用c#将JSON字符串转换为对象。使用一个非常简单的测试用例:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
问题是routes_list从未被设置;它是一个未定义的对象。什么好主意吗?
尝试用c#将JSON字符串转换为对象。使用一个非常简单的测试用例:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
问题是routes_list从未被设置;它是一个未定义的对象。什么好主意吗?
当前回答
另一种快速简单的半自动这些步骤的方法是:
take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down. Update the name in the top left to your class name, it defaults to "Welcome". In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft. app.quicktype.io generated serialize methods based on Newtonsoft. Alternatively, you can now use code like: WebClient client = new WebClient(); string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF"); var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
其他回答
您可能不想仅仅将routes_list声明为对象类型。它没有。test属性,所以你不会得到一个很好的对象。在这里,您最好定义一个类或结构,或者使用dynamic关键字。
如果您真的希望这段代码像您所拥有的那样工作,您需要知道DeserializeObject返回的对象是string,object的泛型字典。下面是这样做的代码:
var json_serializer = new JavaScriptSerializer();
var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list["test"]);
如果你想使用dynamic关键字,你可以在这里阅读如何使用。
如果你声明一个类或结构,你可以调用Deserialize而不是像这样调用DeserializeObject:
class MyProgram {
struct MyObj {
public string test { get; set; }
}
static void Main(string[] args) {
var json_serializer = new JavaScriptSerializer();
MyObj routes_list = json_serializer.Deserialize<MyObj>("{ \"test\":\"some data\" }");
Console.WriteLine(routes_list.test);
Console.WriteLine("Done...");
Console.ReadKey(true);
}
}
另一种快速简单的半自动这些步骤的方法是:
take the JSON you want to parse and paste it here: https://app.quicktype.io/ . Change language to C# in the drop down. Update the name in the top left to your class name, it defaults to "Welcome". In visual studio go to Website -> Manage Packages and use NuGet to add Json.Net from Newtonsoft. app.quicktype.io generated serialize methods based on Newtonsoft. Alternatively, you can now use code like: WebClient client = new WebClient(); string myJSON = client.DownloadString("https://URL_FOR_JSON.com/JSON_STUFF"); var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
这是一个简单的类,我从各种帖子....拼凑起来它已经测试了大约15分钟,但似乎符合我的目的。它使用JavascriptSerializer来做这项工作,这可以在你的应用程序中引用,使用这篇文章中详细的信息。
下面的代码可以运行在LinqPad测试它:
在LinqPad中右键单击脚本选项卡,并选择“查询” 属性” 在“附加引用”中引用“System.Web.Extensions.dll” 的“附加名称空间导入” “System.Web.Script.Serialization”。
希望能有所帮助!
void Main()
{
string json = @"
{
'glossary':
{
'title': 'example glossary',
'GlossDiv':
{
'title': 'S',
'GlossList':
{
'GlossEntry':
{
'ID': 'SGML',
'ItemNumber': 2,
'SortAs': 'SGML',
'GlossTerm': 'Standard Generalized Markup Language',
'Acronym': 'SGML',
'Abbrev': 'ISO 8879:1986',
'GlossDef':
{
'para': 'A meta-markup language, used to create markup languages such as DocBook.',
'GlossSeeAlso': ['GML', 'XML']
},
'GlossSee': 'markup'
}
}
}
}
}
";
var d = new JsonDeserializer(json);
d.GetString("glossary.title").Dump();
d.GetString("glossary.GlossDiv.title").Dump();
d.GetString("glossary.GlossDiv.GlossList.GlossEntry.ID").Dump();
d.GetInt("glossary.GlossDiv.GlossList.GlossEntry.ItemNumber").Dump();
d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef").Dump();
d.GetObject("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso").Dump();
d.GetObject("Some Path That Doesnt Exist.Or.Another").Dump();
}
// Define other methods and classes here
public class JsonDeserializer
{
private IDictionary<string, object> jsonData { get; set; }
public JsonDeserializer(string json)
{
var json_serializer = new JavaScriptSerializer();
jsonData = (IDictionary<string, object>)json_serializer.DeserializeObject(json);
}
public string GetString(string path)
{
return (string) GetObject(path);
}
public int? GetInt(string path)
{
int? result = null;
object o = GetObject(path);
if (o == null)
{
return result;
}
if (o is string)
{
result = Int32.Parse((string)o);
}
else
{
result = (Int32) o;
}
return result;
}
public object GetObject(string path)
{
object result = null;
var curr = jsonData;
var paths = path.Split('.');
var pathCount = paths.Count();
try
{
for (int i = 0; i < pathCount; i++)
{
var key = paths[i];
if (i == (pathCount - 1))
{
result = curr[key];
}
else
{
curr = (IDictionary<string, object>)curr[key];
}
}
}
catch
{
// Probably means an invalid path (ie object doesn't exist)
}
return result;
}
}
使用动态对象JavaScriptSerializer。
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
//test Result = "some data"
添加这个ddl来引用您的项目:System.Web.Extensions.dll
使用System.Web.Script.Serialization;
public class IdName
{
public int Id { get; set; }
public string Name { get; set; }
}
string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);
string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);