编程语言
首页 > 编程语言> > C#-Json.net:通过对象ID合并两个json数组

C#-Json.net:通过对象ID合并两个json数组

作者:互联网

例如,我想通过对象id来破坏json数组.假设我有这个json数组:

 [{"Id":"1", "a":"1", "b":"2"},
  {"Id":"2", "a":"3", "b":"1"},
  {"Id":"3", "a":"5", "b":"1"}]

我想用这个数组来Upsert

 [{"Id":"1", "a":"32", "b":"42"},
 {"Id":"2", "a":"3", "b":"1", "c":"23"},
  {"Id":"12", "a":"12", "b":"45"}]

预期结果应为:

[{"Id":"1", "a":"32", "b":"42"},
  {"Id":"2", "a":"3", "b":"1", "c":"23"},
  {"Id":"3", "a":"5", "b":"1"},
  {"Id":"12", "a":"12", "b":"45"}]

解决方法:

我认为可以使用C#轻松完成.如果将实体映射到类似这样的对象:

[DataContract]
public class Entity
{
    [DataMember(Name = "Id")]
    public string Id { get; set; }

    [DataMember(Name = "a")]
    public int? A { get; set; }

    [DataMember(Name = "b")]
    public int? B { get; set; }

    [DataMember(Name = "c")]
    public int? C { get; set; }
}

我认为无法使用LINQ来执行所需的操作,但是良好的foreach可以解决您的问题.

编辑:实际上,在查看@ vadim-gremyachev答案后,我认为可以很好地使用LINQ来完成:

var l1 = JsonConvert.DeserializeObject<IList<Entity>>(
    @"[{""Id"":""1"", ""a"":""1"", ""b"":""2""}, 
       {""Id"":""2"", ""a"":""3"", ""b"":""1""}, 
       {""Id"":""3"", ""a"":""5"", ""b"":""1""}]");

var l2 = JsonConvert.DeserializeObject<IList<Entity>>(
    @"[{""Id"":""1"", ""a"":""32"", ""b"":""42""},
       {""Id"":""2"", ""a"":""3"", ""b"":""1"", ""c"":""23""},
       {""Id"":""12"", ""a"":""12"", ""b"":""45""}]");

// LINQ
var res = l1.Concat(l2).GroupBy(x => x.Id).Select(x => x.Last()).ToList();

// Foraech
var res2 = new List<Entity>(l1);
foreach (var l2Entity in l2)
{
    var resEntity = res2.FirstOrDefault(x => x.Id == l2Entity.Id);
    if (resEntity == null)
    {
        res2.Add(l2Entity);
    }
    else
    {
        res2[res2.IndexOf(resEntity)] = l2Entity;
    }
}

然后,您只需将res列表序列化回JSON,即可完成:

var json = JsonConvert.SerializeObject(res);

生成的JSON将为:

[
    {"Id":"1","a":32,"b":42},
    {"Id":"2","a":3,"b":1,"c":23},
    {"Id":"3","a":5,"b":1},
    {"Id":"12","a":12,"b":45}
]

您也可以使用l1而不创建res,这当然取决于您的情况.合并完成后,您可能还想按键对结果集合进行排序.

标签:json-net,json,c
来源: https://codeday.me/bug/20191120/2044949.html