JAVA-JSON转对象和对象转JSON

最近遇到JSON转换问题,做下笔记。

工具包为阿里fastjson

    com.alibaba
    fastjson
    1.2.44

1.JSON转对象

//平时我们情况应该是对方发送String给我们,然后我们接受后转换成JSONObject 
//但是使用String的话测试的时候写法是这样的:"{\"name\":\"value\",....}",很容易写错,所以采用以下方式
//String jsonStr = "{\"amount\":\"0.01\",\"currency\":\"USD\",\"body\":\"test\",\"category\":\"0724\"}";
//JSONObject map= JSONObject.parseObject(jsonStr);

JSONObject map=new JSONObject();
map.put("body", "test");
map.put("amount", "0.01");
map.put("currency", "USD");
map.put("category", "0724");
//JSON内容为:{"amount":"0.01","currency":"USD","body":"test","category":"0724"}
TestBean bean = map.toJavaObject(map,TestBean.class);

TestBean类

public class TestBean {
    String body;
    String amount;
    String currency;
    String category;
    ........
    }

2.JSON转数组

//JSON数组
String jsonStr= "[{\"goodsId\":\"apple-01\",\"goodsName\":\"ipad\",\"goodsCategory\":\"7788230\",\"price\":\"2000.00\",\"quantity\":\"1\",\"showUrl\":\"http://www.taobao.com\"},{\"goodsId\":\"apple-01\",\"goodsName\":\"ipad\",\"goodsCategory\":\"7788230\",\"price\":\"2000.00\",\"quantity\":\"1\",\"showUrl\":\"http://www.taobao.com\"}]";
JSONArray goodsDetailJson = JSONObject.parseArray(jsonStr);
//将JSON数组转换成数组对象
List goodsDetail = goodsDetailJson.toJavaObject(goodsDetailJson, List.class);

GoodsDetail类

public class GoodsDetail
{
    private String goodsId;
    private String goodsName;
    private String goodsCategory;
    private String showUrl;
    private String quantity;
    private String body;
    private BigDecimal price;
    .....
}

3.对象转JSON

String jsonStr  = JSONObject.toJSON(bean);

你可能感兴趣的:(JAVA-JSON转对象和对象转JSON)