反序列化特定格式的json字符串



我正在尝试反序列化下面的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()进行反序列化。我无法实现所需的格式。

Ah,所以您有一个结构相同的对象集合,并希望将其转换为类似于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 });
}

相关内容

  • 没有找到相关文章

最新更新