json数组和List转换
Posted 爷的眼睛闪亮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json数组和List转换相关的知识,希望对你有一定的参考价值。
使用的是json-lib.jar包
将json格式的字符数组转为List对象
- package hb;
- import java.util.Date;
- public class Person {
- String id;
- int age;
- String name;
- Date birthday;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- }
- package hb;
- import java.util.Iterator;
- import java.util.List;
- import org.junit.Test;
- import net.sf.json.JSONArray;
- import net.sf.json.JsonConfig;
- public class JsonToList {
- public static void main(String[] args) {
- String json="[{‘name‘:‘huangbiao‘,‘age‘:15},{‘name‘:‘liumei‘,‘age‘:14}]";
- JSONArray jsonarray = JSONArray.fromObject(json);
- System.out.println(jsonarray);
- List list = (List)JSONArray.toCollection(jsonarray, Person.class);
- Iterator it = list.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getAge());
- }
- }
- @Test
- public void jsonToList1(){
- String json="[{‘name‘:‘huangbiao‘,‘age‘:15},{‘name‘:‘liumei‘,‘age‘:14}]";
- JSONArray jsonarray = JSONArray.fromObject(json);
- System.out.println(jsonarray);
- List list = (List)JSONArray.toList(jsonarray, Person.class);
- Iterator it = list.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getAge());
- }
- }
- @Test
- public void jsonToList2(){
- String json="[{‘name‘:‘huangbiao‘,‘age‘:15},{‘name‘:‘liumei‘,‘age‘:14}]";
- JSONArray jsonarray = JSONArray.fromObject(json);
- System.out.println(jsonarray);
- System.out.println("------------");
- List list = (List)JSONArray.toList(jsonarray, new Person(), new JsonConfig());
- Iterator it = list.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getAge());
- }
- }
- }
将list对象转为JSON字符串数组
- package hb;
- import java.util.LinkedList;
- import java.util.List;
- import net.sf.json.JSONArray;
- public class ListToJson {
- public static void main(String[] args) {
- List list = new LinkedList();
- for(int i=0;i<3;i++){
- Person p = new Person();
- p.setAge(i);
- p.setName("name"+i);
- list.add(p);
- }
- JSONArray jsonarray = JSONArray.fromObject(list);
- System.out.println(jsonarray);
- }
- }
打印结果
- [{"age":0,"birthday":null,"id":"","name":"name0"},{"age":1,"birthday":null,"id":"","name":"name1"},{"age":2,"birthday":null,"id":"","name":"name2"}]
以上是关于json数组和List转换的主要内容,如果未能解决你的问题,请参考以下文章
怎样将JAVA中得list集合转换为javascript的二维数组?
(精华)将json数组和对象转换成List和Map(小龙哥和牛徳鹤的对话)