json_Java对象转化

jar包
jackson-annotations-2.2.3.jar
jackson-core-2.2.3.jar
jackson-databind-2.2.3.jar

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import itcast.domain.Person;

public class test1 {

    @Test
    public void run1() throws Exception {

        Person p = new Person("张三", 23, "南通", new Date());
        //创建jackson核心对象
        ObjectMapper mapper = new ObjectMapper();
        //调用方法将Java对象转为Json对象
        String s = mapper.writeValueAsString(p);
        //将json写入文件中
        mapper.writeValue(new File("D://a.txt"),p);
        //将数据写给客户端
        //mapper.writeValue(response.getWriter(),p);
        System.out.println("s:" + s);
    }

    //复杂的数据格式(list)
    @Test
    public void run2() throws Exception {
        Person p = new Person("张三", 23, "南通", new Date());
        Person p1 = new Person("李四", 24, "徐州", new Date());
        Person p2 = new Person("王五", 25, "上海", new Date());

        List<Person> list = new ArrayList<Person>();
        list.add(p);
        list.add(p1);
        list.add(p2);
        //创建jackson核心对象
        ObjectMapper mapper = new ObjectMapper();
        //调用方法将Java对象转为Json对象
        String s = mapper.writeValueAsString(list);
        System.out.println(s);

    }

    //复杂的数据格式(map)
    @Test
    public  void run3() throws Exception {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name","张三");
        map.put("age",23);
        map.put("address","南通");

        //创建jackjson核心对象
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(map);
        System.out.println(s);
    }

    //json转java对象
    @Test
    public void run4() throws Exception {
        String str="{\"address\":\"南通\",\"username\":\"张三\",\"age\":23}";
        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(str, Person.class);
        System.out.println(person);
    }
}

//Java对象

public class Person {
    private String username;
    private int age;
    private String address;

    //忽略转化为json数据
    //@JsonIgnore
    //类似于SimpleDateFormat
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date date;

        ...........

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值