使用C#或JObject或NewtonSoft连接2JSON字符串

vxbzzdmp  于 2023-03-31  发布在  C#
关注(0)|答案(2)|浏览(200)

你好,我有2个JSON文件,我想加入他们

{
    "PropertyOne": "PropOne",
    "PropertyTwo": "PropTwo",
    "PropertyThree": "PropThree"
}

以及

{
    "MyObject": {
        "PropertyOne": "PropOne",
        "PropertyTwo": "PropTwo",
        "PropertyThree": "PropThree"
    }
}

我怎样才能加入他们得到下面的结果,并成为一个有效的json?

{
"PropertyOne": "PropOne",
"PropertyTwo": "PropTwo",
"PropertyThree": "PropThree",
"MyObject": {
    "PropertyOne": "PropOne",
    "PropertyTwo": "PropTwo",
  "PropertyThree": "PropThree"
}

}

ahy6op9u

ahy6op9u1#

我建议使用Newtonsoft。它可以通过Nuget轻松安装。

string json1 = @"{'PropertyOne': 'PropOne','PropertyTwo': 'PropTwo','PropertyThree': 'PropThree'}";
string json2 = @"{'MyObject': {'PropertyOne': 'PropOne','PropertyTwo': 'PropTwo','PropertyThree': 'PropThree'}}";

JObject j1 = JObject.Parse(json1);
JObject j2 = JObject.Parse(json2);

j1.Merge(j2, new JsonMergeSettings {
    MergeArrayHandling = MergeArrayHandling.Union
});

在这里,您将创建两个JSON字符串对象,使用JObject解析它们。然后使用merge方法,您可以让Newtonsoft在幕后处理它。生成的j1对象具有您想要的输出。

xuo3flqw

xuo3flqw2#

试试下面的东西

static void Main(string[] args)
{
    string jsonText = @"
        {
            ""propertyOne"": ""PropOne"",
            ""propertyTwo"": ""PropTwo"",
            ""propertyThree"": ""PropThree""
        }";

    string jsonText2 = @"
        {
            ""propertyOne"": ""PropOne"",
            ""propertyTwo"": ""PropTwo"",
            ""propertyThree"": ""PropThree""
        }";

    var jsonObj = JObject.Parse(jsonText);
    var jsonObj2 = JObject.Parse(jsonText2);

    if (jsonObj != null && jsonObj2 != null)
    {
        if (jsonObj["MyObject"] == null)
        {
            jsonObj.Add("MyObject", new JObject());
        }

        var myObject = jsonObj["MyObject"] as JObject;

        if (myObject != null)
        {
            myObject.Merge(jsonObj2);
        }
    }

    Console.WriteLine(jsonObj.ToString());
}

对我很有效

相关问题