netplex / json-smart-v2

Apache License 2.0
151 stars 68 forks source link

JSONObject.merge blocks overwriting #175

Open hadjiski opened 10 months ago

hadjiski commented 10 months ago

I am starting with an empty JSONObject instance and using the merge method to construct my json over few phases and each of these phases can introduces corrections to the so far prepared json object. For example:

JSONObject json = new JSONObject()
resulting in:
{}

phase 1:

json.merge(<some json object containing two new pairs>)
resulting in:
{
  "k1":"v1",
  "k2":"v2"
}

phase 2:

json.merge(<some json object containing one new pair>)
resulting in:
{
  "k1":"v1",
  "k2":"v2",
  "k3":"v3"
}

phase 3: json.merge() resulting in:

{
  "k1":"changed_v1",
  "k2":"v2",
  "k3":"v3",
  "k4":"v4"
}

Besides the point of correction, the merge method can be perfectly used for this, but when it comes to the correction I am getting: JSON merge can not merge two java.lang.String Object together, which is due to the current implementation by design I guess. Though I don't understand what is the issue with the requirement of being able to overwrite json fields? Maybe to not get into conflicts like overwriting a field which had as a value another complex json structure with a simple string value, but even in such a case, if the intention is to overwrite, then so be it, why not? Or better, keep the strictness, but also offer a more liberal merge as well, which just behaves like the current one, but in case of an impossible merge, just overwrite, what do you think?

Otherwise I would need to fallback to a pure putAll, which will just always overwrite

shoothzj commented 9 months ago

I think we can add params like merge option to custom some behaviors like overwrite. WDYT?