标签:
去除所有格式的json字符串
{"data":[{"friend":[{"address":"广州","name":"好友1"},{"address":"深圳","name":"好友2"}],"username":"包青天"},{"friend":[],"username":"bqt"}],"num":2}
添加转义字符后的json字符串
{\"data\":[{\"friend\":[{\"address\":\"广州\",\"name\":\"好友1\"},{\"address\":\"深圳\",\"name\":\"好友2\"}],\"username\":\"包青天\"},{\"friend\":[],\"username\":\"bqt\"}],\"num\":2}
{ "data": [ { "friend": [ { "address": "广州", "name": "好友1" }, { "address": "深圳", "name": "好友2" } ], "username": "包青天" }, { "friend": [], "username": "bqt" } ], "num": 2 }
public class GsonDemo {
// 将 java 对象 格式化为 Json 字符串.public static void main(String[] args) {Gson gson = new Gson();String json = "{\"data\":[{\"friend\":[{\"address\":\"广州\",\"name\":\"好友1\"},{\"address\":\"深圳\",\"name\":\"好友2\"}],\"username\":\"包青天\"},{\"friend\":[],\"username\":\"bqt\"}],\"num\":2}";GsonBean bean = gson.fromJson(json, GsonBean.class);System.out.println(bean.toString());System.out.println(bean.data.get(0).username);String json2 = gson.toJson(bean);System.out.println("Json字符串 = " + json2);//******************************************************************************************ArrayList<Person> list_person = new ArrayList<Person>();list_person.add(new Person("好友1", "广州"));list_person.add(new Person("好友2", "深圳"));ArrayList<Account> list_account = new ArrayList<Account>();list_account.add(new GsonBean().new Account("包青天", list_person));//外部类GsonBean要有一个无参的构造方法,不然怎么创建内部类对象?list_account.add(new GsonBean().new Account("bqt", new ArrayList<Person>()));//可以是空的集合,或者直接是空对象nullGsonBean bean2 = new GsonBean(2, list_account);String json3 = gson.toJson(bean2);System.out.println("Json字符串 = " + json3);}}
public class Person {
//不要求一定有get、set方法,也不要求一定有无参构造方法,甚至不要求其成员是public还是private//但要求所有字段名必须和json字符串中的一致public String name;public String address;public Person(String name, String address) {this.name = name;this.address = address;}@Overridepublic String toString() {return "name=" + name + " & " + "address=" + address;}}
public class GsonBean {
public GsonBean() {}public GsonBean(int num, ArrayList<Account> data) {super();this.num = num;this.data = data;}public int num;public ArrayList<Account> data;/**data数组里的对象*/public class Account {public String username;public ArrayList<Person> friend;@Overridepublic String toString() {return "账户【username=" + username + ",friend=" + friend + "】";}public Account(String username, ArrayList<Person> friend) {super();this.username = username;this.friend = friend;}}@Overridepublic String toString() {return "Gson 【num=" + num + ",data=" + data + "】";}}
标签:
原文地址:http://www.cnblogs.com/baiqiantao/p/5373273.html