-
Notifications
You must be signed in to change notification settings - Fork 8
Open
Description
Why? so you can merge two json objects and preserve the previous ones data. Note that JSONObject and JSONArray both Implement ICopy.
Code JSONObject:
public void merge(JSONObject other)
{
for(java.util.Map.Entry<Object, Object> entry : other.entrySet())
{
String key = (String) entry.getKey();
Object otherIndex = entry.getValue();
Object thisIndex = this.get(key);
if(thisIndex instanceof JSONObject && otherIndex instanceof JSONObject)
{
JSONObject json = (JSONObject) thisIndex;
json.merge((JSONObject) otherIndex);
}
else if(thisIndex instanceof JSONArray && otherIndex instanceof JSONArray)
{
JSONArray arr = (JSONArray) thisIndex;
arr.merge((JSONArray) otherIndex);
}
else
{
this.put(key, otherIndex instanceof ICopy ? ((ICopy) otherIndex).copy() : otherIndex);
}
}
}
@Override
public JSONObject copy()
{
JSONObject json = new JSONObject(this.size() + 3);
for(java.util.Map.Entry<Object, Object> entry : this.entrySet())
{
String key = (String) entry.getKey();
Object value = entry.getValue();
if(value instanceof ICopy)
json.put(key, ((ICopy) value).copy());
else
json.put(key, value);
}
return json;
}Code JSONArray:
public void merge(JSONArray other)
{
int tsize = this.size();
for(int i=0; i< other.size(); i++)
{
Object otherIndex = other.get(i);
if(i < tsize)
{
Object thisIndex = this.get(i);
if(thisIndex instanceof JSONArray && otherIndex instanceof JSONArray)
{
((JSONArray)thisIndex).merge((JSONArray) otherIndex);
}
else if(thisIndex instanceof JSONObject && otherIndex instanceof JSONObject)
{
((JSONObject)thisIndex).merge((JSONObject) otherIndex);
}
else
this.set(i, otherIndex instanceof ICopy ? ((ICopy) otherIndex).copy() : otherIndex);
}
else
this.add(otherIndex instanceof ICopy ? ((ICopy) otherIndex).copy() : otherIndex);
}
}
@Override
public JSONArray copy()
{
JSONArray arr = new JSONArray(this.size() + 3);
for(int i=0;i<this.size();i++)
{
Object o = this.get(i);
if(o instanceof ICopy)
o = ((ICopy) o).copy();
arr.add(o);
}
return arr;
}Code ICopy:
public interface ICopy{
public ICopy copy();
}Current Issue: if the original's data type doesn't match the other's data type it gets replaced with a copy of the other JSON's data. JSONObject != JSONArray and other JSONObject has a JSONArray at that key then JSONArray replaces JSONObject. A possible solution would be to wrap the JSONObject or JSONArray when that happens according to chatgpt. I wouldn't recommend throwing an error as this is SIMPLE JSON and SIMPLE json isn't suppose to be as strict.
Metadata
Metadata
Assignees
Labels
No labels