转换JSON数组的格式

时间:2018-12-24 02:29:22

标签: c# json

我在下面的SQL Server中有一个jsonObject查询:

{
  "list": [
    {
      "code": "c1_1",
      "value": "1"
    },
    {
      "code": "c1_2",
      "value": false
    }
  ]
}

如何将其格式转换为:

{
  "list": {
    "c1_1": "1",
    "c1_2": false
  }
}

2 个答案:

答案 0 :(得分:3)

您所拥有的是对象的json列表,并且您正在尝试将其转换为字典

还有其他方法可以执行此操作,但是您可以执行此操作

public class Something
{
   public string code { get; set; }
   public object value { get; set; }
}

public class RootObject
{
   public List<Something> List { get; set; }
}

public class NewObject
{
   public Dictionary<string,object> List { get; set; }
}

用法

// convert it to C# concrete classes
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);

// convert to dictionary 
var dictionary = rootObject.List.ToDictionary(x => x.code, x => x.value);

// create new object with dictionary
var newObject = new NewObject() {List = dictionary};

// output
var output = JsonConvert.SerializeObject(newObject, Formatting.Indented);

输出

{
  "List": {
    "c1_1": "1",
    "c1_2": false
  }
}

Full Demo Here


其他资源

  

从IEnumerable创建字典。

答案 1 :(得分:2)

使用Json.Net的Microsoft Documentation,您可以像这样转换JSON:

var obj = JObject.Parse(json);
obj["list"] = new JObject(
    obj["list"].Children<JObject>()
               .Select(jo => new JProperty((string)jo["code"], jo["value"]))
);
json = obj.ToString();

提琴:LINQ-to-JSON API