码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA对象JSON数据互相转换的常见情况

时间:2018-01-26 18:49:05      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:一个   toc   log   泛型   entity   数据   rtl   collect   passport   

1.java对象转成Json数组

JSONArray array=JSONArray.fromObject(javaobject);

将array转成字符串:String  jsonstr=array.toString();

2.java对象转成Json对象

JSONObject jsonobject=JSONObject.fromObject(javaobject);

将jsonobject转成字符串:jsonobject.toString();

3.Json字符串转成java对象数组

String personstr=getRequest().getParameter("personstr");

JSONArray json=JSONArray.fromObject(personstr);

List<Person> persons=(List<Person> )JSONArray.toCollection(json,Person.class);

4.Json字符串转成java对象

JSONObject jsonobject = JSONObject.fromObject(str);

  PassportLendsEntity passportlends = null;
  try {
   //获取一个json数组
   JSONArray array = jsonobject.getJSONArray("passports");
   //将json数组 转换成 List<PassPortForLendsEntity>泛型
   List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
   for (int i = 0; i < array.size(); i++) {   
            JSONObject object = (JSONObject)array.get(i);  
            PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
              PassPortForLendsEntity.class);
            if(passport != null){
             list.add(passport);
            }  
     }
   //转换PassportLendsEntity 实体类
  passportlends = (PassportLendsEntity)JSONObject.toBean(jsonobject, PassportLendsEntity.class);

 

  str = "{\"lendperson\":\"李四\",\"lendcompany\":\"有限公司\",\"checkperson\":\"李四\",

  \"lenddate\":\"2010-07-19T00:00:00\",\"lendcounts\":4,\"
  passports\":[{\"passportid\":\"d\",\"name\":\"李豫川\",\"passporttype\":\"K\"},
  {\"passportid\":\"K9051\",\"name\":\"李平\",\"passporttype\":\"K\"},
  {\"passportid\":\"K90517\",\"name\":\"袁寒梅\",\"passporttype\":\"K\"},
  {\"passportid\":\"K905199\",\"name\":\"贺明\",\"passporttype\":\"K\"}]}";

 

JAVA对象JSON数据互相转换的常见情况

标签:一个   toc   log   泛型   entity   数据   rtl   collect   passport   

原文地址:https://www.cnblogs.com/onyli/p/8360618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!