Athony

Springboot gson转换工具 将json格式的字符串转换为list
举个例子: 对象 entity类 public class Person { private Strin...
扫描右侧二维码阅读全文
17
2019/06

Springboot gson转换工具 将json格式的字符串转换为list

举个例子:

  • 对象 entity类

    public class Person {  
    
    private String name;  
    private int age;  
    
    /** 
     * @return the name 
     */  
    public String getName() {  
        return name;  
    }  
    
    /** 
     * @param name the name to set 
     */  
    public void setName(String name) {  
        this.name = name;  
    }  
    
    /** 
     * @return the age 
     */  
    public int getAge() {  
        return age;  
    }  
    
    /** 
     * @param age the age to set 
     */  
    public void setAge(int age) {  
        this.age = age;  
    }  
    
    @Override  
    public String toString()  
    {  
        return name + ":" +age;  
    }  
    }
  • 测试类

    Gson gson = new Gson();  
    List<Person> persons = new ArrayList<Person>();  
    for (int i = 0; i < 10; i++) {  
     Person p = new Person();  
     p.setName("name" + i);  
     p.setAge(i * 5);  
     persons.add(p);  
    }  
    String str = gson.toJson(persons);
  • 打印结果:
  • [{"name":"name0","age":0},{"name":"name1","age":5},{"name":"name2","age":10},{"name":"name3","age":15},{"name":"name4","age":20},{"name":"name5","age":25},{"name":"name6","age":30},{"name":"name7","age":35},{"name":"name8","age":40},{"name":"name9","age":45}]

  • json 转换 单一实体:
  • 例如 [{"name":"name0","age":0}]
Person person = gson.fromJson(str, Person.class);  
  • 转换成list :
List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());  
for(int i = 0; i < ps.size() ; i++)  {  
     Person p = ps.get(i);  
     System.out.println(p.toString());  
}

list里面就是上面那个结果:
[{"name":"name0","age":0},{"name":"name1","age":5},{"name":"name2","age":10},{"name":"name3","age":15},{"name":"name4","age":20},{"name":"name5","age":25},{"name":"name6","age":30},{"name":"name7","age":35},{"name":"name8","age":40},{"name":"name9","age":45}]
就是说有这9个person对象的list

最后修改:2019 年 06 月 18 日 12 : 09 AM
如果觉得我的文章对你有用,请随意赞赏

发表评论

2 条评论

  1. wz

  2. wz

© 2018-2019 Copyright   | 浙ICP备18047860号-1| SiteMap