在网上找了一下,发现都是遍历两个JSONObject,再将他们各个取出来合并。
感觉有点麻烦,突然灵光乍现,两个JSONObject开始是String,中途转换成JSONObject对数据进行添加操作后又转换成String,所以我就取了个巧,不去操作JSONObject,而是从String入手,合并两个JSONObject的字符串,然后截取掉中间的}{替换成,防止转换异常
public static void main(String[] args) {
String JSONObjectString2 = "{\"axisx\": \"90\",\"axisy\": \"-90\",\"axisy3\": \"相同2\"}";
String JSONObjectString1 = "{\"axisx1\": \"90\",\"axisy2\": \"-90\",\"axisy3\": \"相同1\"}";
String note12 = JSONObjectString2+ JSONObjectString1;
if(note12.contains("}{")){
note12 = note12.replace("}{", ",");
}
JSONObject jsonObject = JSONObject.parseObject(note12);
System.out.println(jsonObject);
}
输出结果:如果key相同,取第二个key的值
相同key的例子:
{"axisy":"-90","axisx":"90","axisx1":"90","axisy2":"-90","axisy3":"相同1"}