【问题标题】:Deserialize a json string in specific format以特定格式反序列化 json 字符串
【发布时间】:2016-07-18 22:35:58
【问题描述】:

我正在尝试反序列化下面的 JSON 字符串:

[{"Code1":"AA","Code2":"AB"},{"Code1":"BB","Code2":"BC"},
 {"Code1":"A1","Code2":"A12"},{"Code1":"A2","Code2":"A23"},
 {"Code1":"A4","Code2":"A45"},{"Code1":"A3","COde2":"A45"}]

改成如下格式:

{"Header":["Code1","Code2"], "Values":[["AA","AB"],["BB","BC"],["A1","A12"],["A2","A23"],["A4","A45"],["A3","A45"]]}

我正在尝试使用JsonConvert.DeseriaizeObject() 反序列化。我无法实现所需的格式。

【问题讨论】:

  • 您使用哪种语言进行转换? C#?请用它标记您的问题。
  • 我正在使用 C# 和 mvc 或者我也有兴趣知道这是否可以通过 web api 实现

标签: c# json asp.net-mvc json.net


【解决方案1】:

啊,所以您有一组结构相同的对象,并且想将其转换为类似于 CSV 表的东西(标题序列,然后是记录序列)?

您可以使用以下方法从对象集合格式转换为记录表格式:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

//other code, class declaration etc. goes here

string ObjectsToTable(string collectionJson)
{
    // reading the collection from passed JSON string
    JArray collection = JArray.Parse(collectionJson);

    // retrieving header as a list of properties from the first element
    // it is assumed all other elements have the exact same properties
    List<string> header = (collection.First as JObject).Properties().Select(p => p.Name).ToList();

    // retrieving values as lists of strings
    // each string is corresponding to the property named in the header
    List<List<string>> values = collection.Children<JObject>().Select( o => header.Select(p => o[p].ToString()).ToList() ).ToList();

    // passing the table structure with the header and values
    return JsonConvert.SerializeObject(new { Header = header, Values = values });
}

【讨论】:

  • 遗憾的是,我对 ASP.NET MVC 视图了解不多;我自己只使用过 Web API。至于在没有 Linq 的情况下这样做:我认为这是可能的,但过于冗长。您不想为此使用 Linq 有什么特别的原因吗?
  • 通常,在正确配置的 Web API 中,您可以从对象创建 HTTP 响应,它会自动将对象序列化为 JSON。在这种情况下,您只需从“new { Header = header, Values = values }”部分创建一个 HTTP 响应。因此,如果您想在 Web API 中执行此操作,我建议寻找有关 Web API 的一般教程,学习如何通过控制器方法传递对象,然后将这些知识与我在答案中提供的方法一起应用。 ;)
猜你喜欢
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多