方法为,把两个拼装好的JSON串合并成一个新的JSON,两个JSON相同的key值情况下只保存一个,后放入的JSON串对应key的Value值会覆盖先放入的。
具体操作设置方法为
import net.sf.json.JSONObject;
public class JSONCombine
{
public static void main(String[] args)
{
JSONObject jsonOne = new JSONObject();
JSONObject jsonTwo = new JSONObject();
jsonOne.put("name", "kewen");
jsonOne.put("age", "24");
jsonTwo.put("hobbit", "Dota");
jsonTwo.put("hobbit2", "wow");
JSONObject jsonThree = new JSONObject();
jsonThree.putAll(jsonOne);
jsonThree.putAll(jsonTwo);
System.out.println(jsonThree.toString());
}
}
运行结果:
{"name":"12345","age":"24","hobbit":"Dota","hobbit2":"wow"}
json转object示例
ObjectMapper objectMapper = new ObjectMapper();
YourClass class = objectMapper.readValue(YourJson, YourClass.class);
如果json中有新增的字段并且是YourClass类中不存在的,则会转换错误。
1)需要加上如下语句,这种方法的好处是不用改变要转化的类
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
YourClass class = objectMapper.readValue(YourJson, YourClass.class);
2)jackson库还提供了注解方法,用在class级别上
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class YourClass {
...
}