将字段附加到Json记录对象

时间:2015-04-21 14:56:14

标签: c# asp.net .net json json.net

我正在使用Newtonsoft的Json.Net。 我有这个Json:

var j1 = {"status_code":"200", "message":"everything is ok"};

这是另一个Json:

var j2 = {"records":[{"id":"1", "name":"file1"},
                      {"id":"2", "name":"file2"},
                      {"id":"3", "name":"file3"}]
         }; 

基本上第二个j2是目录中文件的列表(数组)。 它可能是空的:

 {"records":"[]"}

我想要的是:将j2追加(concat,merge)j1到j1的结尾:

var j3 = {
          "status_code":"200", 
          "message":"everything is ok", 
          "records":[{"id":"1", "name":"file1"},
                      {"id":"2", "name":"file2"},
                      {"id":"3", "name":"file3"}]
         };
         // NOTE: the array does NOT have double quots ("")

如何使用JsonConvert.Serialize()或Newtonesoft的Json.NET中的任何其他方式实现此目的?

5 个答案:

答案 0 :(得分:0)

var j = JsonConvert.SerializeObject(new[] { JsonConvert.DeserializeObject(j1), 
JsonConvert.DeserializeObject(j2) });

var j = JsonConvert.SerializeObject(new { obj1 = JObject.Parse(j1), 
                                          obj2 = JObject.Parse(j2) });

答案 1 :(得分:0)

可以试试这个(注意:没有空的检查......):

string json1 = "{\"status_code\":\"200\",\"message\":\"everything is ok\"}";
string json2 = "{\"records\":[{\"id\":\"1\",\"name\":\"file1\"},{\"id\":\"2\",\"name\":\"file2\"},{\"id\":\"3\",\"name\":\"file3\"}]}";

dynamic object1 = JsonConvert.DeserializeObject(json1);
dynamic object2 = JsonConvert.DeserializeObject(json2);

dynamic result = object1;
result.records = object2.records;

string serialized = JsonConvert.SerializeObject(result);

答案 2 :(得分:0)

这可能有用。

var j3 = j1.concat(j2);

答案 3 :(得分:0)

这些答案大大超过了复杂的事情......只需创建一个新的匿名类型内联,你调用SerializeObject,它看起来像这样;

  string serialized = JsonConvert.SerializeObject(new { status_code = j1.status_code, 
                                                        message = j1.message,
                                                        records = j2.records } );                                            

答案 4 :(得分:0)

您可以使用LINQ to JSON中构建的JSON.NET来实现此目的:

string j1 = {"status_code":"200", "message":"everything is ok"};
string j2 = {"records":[{"id":"1", "name":"file1"},
                          {"id":"2", "name":"file2"},
                          {"id":"3", "name":"file3"}]
             }; 

JObject jObject1 = JObject.Parse(j1);
JObject jObject2 = JObject.Parse(j2);

jObject1.Merge(jObject2, new JsonMergeSettings
                {
                    MergeArrayHandling = MergeArrayHandling.Concat
                });

string j3 = jObject1.ToString();

j3变量看起来完全如下:

{
    "status_code": "200",
    "message": "everything is ok",
    "records": [
        {
            "id": "1",
            "name": "file1"
        },
        {
            "id": "2",
            "name": "file2"
        },
        {
            "id": "3",
            "name": "file3"
        }
    ]
}

这就是你想要的。