工作中用的蛮多的最近整理下,概括地说 通过这个工具可以让一个json在json串,JSONObject,java对象之间进行转化
首先我们先写2个bean来构成一个比较复杂的json串:
public class InnerBean { private String nickname; private String workcity; public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getWorkcity() { return workcity; } public void setWorkcity(String workcity) { this.workcity = workcity; } }
import java.util.List; public class TestBean { private String name; private Integer value; private boolean beTrue; private long number; private InnerBean innerBean; private List<InnerBean> innerBeanList; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public long getNumber() { return number; } public void setNumber(long number) { this.number = number; } public boolean isBeTrue() { return beTrue; } public void setBeTrue(boolean beTrue) { this.beTrue = beTrue; } public InnerBean getInnerBean() { return innerBean; } public void setInnerBean(InnerBean innerBean) { this.innerBean = innerBean; } public List<InnerBean> getInnerBeanList() { return innerBeanList; } public void setInnerBeanList(List<InnerBean> innerBeanList) { this.innerBeanList = innerBeanList; } }
接着是相关的转换:
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.Arrays; public class JsonObject { public static void main(String[] args) { TestBean testBean=new TestBean(); testBean.setName("test"); testBean.setNumber(123); testBean.setBeTrue(true); testBean.setValue(321); InnerBean innerBean=new InnerBean(); innerBean.setNickname("dasda"); innerBean.setWorkcity("asdasd"); testBean.setInnerBean(innerBean); testBean.setInnerBeanList(Arrays.asList(innerBean,innerBean)); //对象转json String beanToString=JSONObject.toJSONString(testBean); System.out.println("=======对象转json"+beanToString+"========"); //json串转JSONObject JSONObject jsonObject=JSONObject.parseObject(beanToString); //异常:字符串类型值test不能转 // jsonObject.getDate("name"); Object object=jsonObject.get("name"); if (object instanceof JSONObject){ System.out.println("=======JsonObject type========="); } System.out.println("name的值为:"+object.toString()); Object innerBeanObj=jsonObject.getJSONObject("innerBean"); if (innerBeanObj instanceof JSONObject){ System.out.println("======="+"innerBean的类型为"+"JsonObject type========="); } System.out.println(innerBeanObj.toString()); JSONArray array= jsonObject.getJSONArray("innerBeanList"); array.forEach(obj->{ if (obj instanceof JSONObject){ System.out.println("======="+"innerBeanList的类型为"+"JsonObject type========="); System.out.println(obj.toString()); } }); } }