在C#中将字符串转换为JSON

行程

我正在尝试使用简单JSON将此字符串转换为JSON:

"{\"objects\":[{\"id\":1,\"title\":\"Book\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:22.817Z\"},{\"id\":2,\"title\":\"Apple\",\"position_x\":0,\"position_y\":0,\"position_z\":0,\"rotation_x\":0,\"rotation_y\":0,\"rotation_z\":0,\"created\":\"2016-09-21T14:22:52.368Z\"}]}"

不幸的是,似乎Visual Studio没有Interactive Debugging Console。与之类似,将调试器放在一行上,然后在实时交互式控制台中进入该部分代码。在其他方面,我将能够使用SimpleJSON的库进行实验,并了解如何使它工作。如果我错了,一定要纠正我!

由于那是不可能的,有人会知道如何做到这一点吗?我已经试过了

JSONData jsonData = new JSONData(my_json_string);

但这会使字符串更多地转义并保留为字符串:

"\"{\\\"objects\\\":[{\\\"id\\\":1,\\\"title\\\":\\\"Book\\\",\\\"position_x\\\":0,\\\"position_y\\\":0,\\\"position_z\\\":0,\\\"rotation_x\\\":0,\\\"rotation_y\\\":0,\\\"rotation_z\\\":0,\\\"created\\\":\\\"2016-09-21T14:22:22.817Z\\\...

我是C#的新手,但令我感到惊讶的是,C#本身没有什么东西比解析JSON更通用。有一个吗?

维希尼克(M.Wiśnicki)

首先,创建数据模型。您可以使用非常有用的工具json2sharp

public class Item
{
    public int id { get; set; }
    public string title { get; set; }
    public int position_x { get; set; }
    public int position_y { get; set; }
    public int position_z { get; set; }
    public int rotation_x { get; set; }
    public int rotation_y { get; set; }
    public int rotation_z { get; set; }
    public string created { get; set; }
}

下次使用Newtonsoft.Json并调用反序列化方法。

var list = JsonConvert.DeserializeObject<List<Item>>(Yourjson);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章