1

I have multiple instances of JSON objects that have missing or updated information. I want a way to take all of the JSON objects and combine them into one record in C# (.net 3.5). If there is an existing field, I want the latest one saved.

for example, if I had all of these objects respectively:

{
    "id" : 1,
    "firstName" : "John",
}
{
    "id" : 1,
    "firstName" : "John",
    "lastName" : "Dow",
    "phone" : "555-555-5555"
}
{
    "id" : 1,
    "phone" : "(555) 555-555"
}
    "id" : 1,
    "position" : "Peon"
}

I would want a resulting object equal to:

{
    "id" : 1,
    "firstName" : "John",
    "lastName" : "Dow",
    "phone" : "(555) 555-555"
    "position" : "Peon"
}

Thank you for any help!

joe_coolish
  • 7,201
  • 13
  • 64
  • 111
  • 2
    What happens if there are inconsistencies? Would that be an exception condition? – Pete M Apr 04 '11 at 17:08
  • 2
    You may want to look at [Does C# have a library for parsing multi-level cascading JSON?](http://stackoverflow.com/questions/4002508/does-c-have-a-library-for-parsing-multi-level-cascading-json), though it's not exactly the same question. – Matthew Flaschen Apr 04 '11 at 17:11
  • Inconsistencies should be overwritten by the newest data. I guess I should also say that "id" is the indexable variable. As long as "id" is the same, it should cascade. @Matthew - I'll look into the post! That looks about like what I want to do :) – joe_coolish Apr 04 '11 at 17:22
  • Possible duplicate of [Merge two Json.NET arrays by concatenating contained elements](https://stackoverflow.com/questions/14121010/merge-two-json-net-arrays-by-concatenating-contained-elements) – Michael Freidgeim Sep 21 '17 at 11:11

1 Answers1

-1

If doing it in javascript is an option for you prior to c# working with the set then you could use underscore.js. I don't include any checking to see if id is the same so if this may be the case this needs to be added

var objects = [
{
    "id" : 1,
    "firstName" : "John"
},
{
    "id" : 1,
    "firstName" : "John",
    "lastName" : "Dow",
    "phone" : "555-555-5555"
},
{
    "id" : 1,
    "phone" : "(555) 555-555"
},
{
    "id" : 1,
    "position" : "Peon"
}];

var merged = _.reduce(objects, function(sum, value){ return _.extend(sum, value); }, {});

gives

{
 "id":1,
 "firstName":"John",
 "lastName":"Dow",
 "phone":"(555) 555-555",
 "position":"Peon"
}
James Kyburz
  • 13,775
  • 1
  • 32
  • 33