简体   繁体   English

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

[英]Joining 2 json string using c# or jobject or newtonsoft

Hi given I have 2 json files and I would like to join them 您好,我有2个json文件,我想加入他们

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

and

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

How can I join them get the below outcome and be a valid json? 我如何加入他们的行列,得到以下结果并成为有效的json?

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

} }

I would suggest using Newtonsoft. 我建议使用Newtonsoft。 It is available via Nuget for easy install. 它可以通过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
});

Here you would create your two JSON string objects, parse both of them using JObject. 在这里,您将创建两个JSON字符串对象,并使用JObject解析它们。 Then using the merge method you can let Newtonsoft take care of it behind the scenes. 然后,使用merge方法,可以让Newtonsoft在后台处理它。 The resulting j1 object has your desired output. 生成的j1对象具有所需的输出。

try below thing 尝试下面的事情

static void Main(string[] args)
    {

        string jsonText = @"
                          {
                            ""PropertyOne"": ""PropOne"",
                            ""PropertyTwo"": ""PropTwo"",
                            ""PropertyThree"": ""PropThree""
                        }";

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

        var JsonObj = JObject.Parse(jsonText);
        var JsonObj2 = JObject.Parse(jsonText2);

        JObject MyObject = JsonObj as JObject;

        MyObject.Add("MyObject", JsonObj2["MyObject"]);

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

it's working for me 它为我工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM