如何使用 JObject.FromObject 获得没有属性名的 json

How to use JObject.FromObject to get a json with no propertyname

我使用 NewtonSoft JSON.Net。我有一个名称值对的集合,我需要得到一个看起来像的 json {"cot":"1","mac":"2","cot":"8"} 请注意,我可以在这里重名。

我这里有两个选择 a) 我可以使用 Dictionary 作为我的基础集合,当我这样做时,我得到了想要的结果,但我不能添加重复的键。 b) 我有一个 KeyValuePair 列表,但在这种情况下,结果 json 不在我想要的结构中。

知道如何获得想要的结果吗?谢谢!

        var listData = new List<KeyValuePair<string, string>>();
        listData.Add(new KeyValuePair<string, string>("cot", "1"));
        listData.Add(new KeyValuePair<string, string>("mat", "1"));
        listData.Add(new KeyValuePair<string, string>("cot", "2"));

        var dicData = new Dictionary<string, string>();
        dicData.Add("cot", "1");
        dicData.Add("mat", "1");

        Console.WriteLine("Output from LIST");
        Console.WriteLine(JArray.FromObject(listData));
        Console.WriteLine();
        Console.WriteLine("Output from Dictionary");
        Console.WriteLine(JObject.FromObject(dicData));

来自 LIST 的输出

[
  {
    "Key": "cot",
    "Value": "1"
  },
  {
    "Key": "mat",
    "Value": "1"
  },
  {
    "Key": "cot",
    "Value": "2"
  }
]

字典输出

{
  "cot": "1",
  "mat": "1"
}

JSON '{"cot":"1","mac":"2","cot":"8"}' 将解析为一个 javscript 对象: {"cot":"8","mac":"2"}

试试看 dicData.Add("cot", "8") 看看它是否得到你想要的。

您也可以尝试连接字符串,直到获得所需的 JSON。 喜欢

var jsonOutput = "{"
//for each key value...
jsonOutput += "key : "+ value.toString + ","
//...etc
//then remove the last trailing comma, and add a "}"