您的位置:首页 > 编程语言 > Java开发

关于Gson的各数据类型转换

2016-02-27 20:11 591 查看
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库

下面是自己总结的各种数据类型的处理方式,包括:

1,单个实体对象转换为JSON格式

2,带泛型的实体对象集合转换为为JSON

3,单个JSONString转换为实体对象

4,集合型JSON转换为实体对象集合

5,实体对象Map集合转换为Map集合型JSON

6,Map集合型JSON转换为实体对象Map集合

        附上完整下面的Eclipse项目代码包免费下载链接: http://download.csdn.net/detail/zjluocisoftstone/9446205,链接最底下也有

下面是我做演示写的一个对象实体类PeopleEntry:

public class PeopleEntry {
private int id;
private String name;
private int age;
private String province;
private String phoneNum;
private String address;

public PeopleEntry(int id, String name, int age, String province, String phoneNum, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.province = province;
this.phoneNum = phoneNum;
this.address = address;
}

public PeopleEntry() {
super();
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getProvince() {
return province;
}

public void setProvince(String province) {
this.province = province;
}

public String getPhoneNum() {
return phoneNum;
}

public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "PeopleEntry \n[ id=" + id + ",\n name=" + name + ",\n age=" + age + ",\n province=" + province + ",\n phoneNum="
+ phoneNum + ",\n address=" + address + "]\n";
}

}
另外为了方便演示,写了一个类RandomPeopleEntryList,只有一个公开静态方法getRandomPeopleEntryList(int size),就是获取任意数量具有随机信息的实体对象PeopleEntry集合
import java.util.ArrayList;
import java.util.List;

public class RandomPeopleEntryList {
private static final String[] FirstName = new String[] { "张", "罗", "牛", "刘", "梁", "李", "章", "欧阳", "慕容", "成", "段",
"肖" };
private static final String[] SecondName = new String[] { "亮", "聪", "莉", "贵", "勇", "风", "峰" };
private static final String[] ProvinceArray = { "北京", "上海", "天津", "重庆", "河北", "山西", "内蒙", "辽宁", "吉林", "黑龙江", "江苏",
"浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南", "广东", "广西", "海南", "四川", "贵州", "云南", "西藏", "陕西", "甘肃", "宁夏",
"青海", "新疆", "香港", "澳门", "台湾" };
private static final String[] PhoneNum_Start_Num = { "130", "131", "132", "133", "134", "135", "136", "137", "138",
"139", "158", "159", "150", "188", "189" };
/**
* 获得随机size个人实体集合
* @param size
* @return List<PeopleEntry>
*/
public static List<PeopleEntry> getRandomPeopleEntryList(int size) {
List<PeopleEntry> peopleList = new ArrayList<PeopleEntry>();
for (int i = 0; i < size; i++) {
String name = randomGetName();
String phoneNum = randomGetPhoneNum();
peopleList.add(new PeopleEntry(i, name, (int) (Math.random() * 100),
ProvinceArray[(int) (Math.random() * ProvinceArray.length)], phoneNum,
ProvinceArray[(int) (Math.random() * ProvinceArray.length)] + (int) (Math.random() * 10000) + "号"));
}
return peopleList;
}

private static String randomGetName() {
int firstNum, secondNum;
firstNum = (int) (Math.random() * FirstName.length);
secondNum = (int) (Math.random() * SecondName.length);
String name = FirstName[firstNum] + SecondName[secondNum];
return name;
}

private static String randomGetPhoneNum() {
String phoneNumStartNum = PhoneNum_Start_Num[(int) (Math.random() * PhoneNum_Start_Num.length)];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; i++) {
String num = "" + (int) (Math.random() * 10);
sb.append(num);
}
return phoneNumStartNum + sb.toString();
}

}

接下来就是各个Gson的数据转换演示实例类GsonTest
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

public class GsonTest {
public static void main(String[] args) {
List<PeopleEntry> peopleEntryList = RandomPeopleEntryList.getRandomPeopleEntryList(5);
Gson gson = new Gson();
// 转换单个实体对象
System.out.println("---------转换单个实体对象--------------");
System.out.println(gson.toJson(peopleEntryList.get(0)));

// 转换整个带泛型的集合
System.out.println("\n----------转换整个带泛型的集合------------");
String jsonArray = gson.toJson(peopleEntryList);
System.out.println(jsonArray);

// 单个JsonString转换为实体对象
System.out.println("\n---------单个JsonString转换为实体对象----");
String singleJsonString = gson.toJson(peopleEntryList.get(4));
PeopleEntry singlePeopleEntry = gson.fromJson(singleJsonString, PeopleEntry.class);
System.out.println(singlePeopleEntry);

System.out.println("\n-------------集合型JSON转换为对象集合-----------");
// 集合型JSON转换为对象集合
try {
System.out.println(readerJsonArrayToList(jsonArray));
} catch (Exception e) {
e.printStackTrace();
System.out.println("解析出错!");
}
//集合型JSON转换为对象集合2
System.out.println("\n-------------集合型JSON转换为对象集合2-----------");
System.out.println(parseJsonArrayToList(jsonArray));

//对象Map集合转换为Map集合型JSON
System.out.println("\n-------------对象Map集合转换为Map集合型JSON-----------");
Gson gson2 = new GsonBuilder().enableComplexMapKeySerialization().create();
Map<String, PeopleEntry> map = new LinkedHashMap<String, PeopleEntry>();
map.put("第二个", peopleEntryList.get(2));
map.put("第一个", peopleEntryList.get(1));
String jsonMapString = gson2.toJson(map, new TypeToken<LinkedHashMap<String, PeopleEntry>>() {
}.getType());
System.out.println(jsonMapString);

//Map集合型JSON转换为对象Map集合
System.out.println("\n-------------Map集合型JSON转换为对象Map集合-----------");
LinkedHashMap<String, PeopleEntry> map2 = gson2.fromJson(jsonMapString,
new TypeToken<LinkedHashMap<String, PeopleEntry>>() {
}.getType());
for (Iterator<String> iterator = map2.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
PeopleEntry value=map2.get(key);
System.out.println("key:"+key+" value:"+value);

}
}
/**
* JSON数组转换为实体对象集合的第一种方法
* @param jsonArray
* @return
*/
public static List<PeopleEntry> parseJsonArrayToList(String jsonArray) {
TypeToken<List<PeopleEntry>> list = new TypeToken<List<PeopleEntry>>() {
};
Gson gson = new Gson();
return gson.fromJson(jsonArray, list.getType());
}
/**
* JSON数组转换为实体对象集合的第二种方法
* @param jsonArray
* @return
* @throws Exception
*/
public static List<PeopleEntry> readerJsonArrayToList(String jsonArray) throws Exception {
JsonReader jsonReader = new JsonReader(new StringReader(jsonArray));
List<PeopleEntry> peopleEntries = null;
jsonReader.beginArray();
peopleEntries = new ArrayList<>();
while (jsonReader.hasNext()) {
peopleEntries.add(readerJsonObjectToObject(jsonReader));
}
jsonReader.endArray();
return peopleEntries;
}

private static PeopleEntry readerJsonObjectToObject(JsonReader jsonReader) throws Exception {
int id = 0;
String name = null;
int age = 0;
String province = null;
String phoneNum = null;
String address = null;
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if ("id".equals(key)) {
id = jsonReader.nextInt();
} else if ("name".equals(key)) {
name = jsonReader.nextString();
} else if ("age".equals(key)) {
age = jsonReader.nextInt();
} else if ("province".equals(key)) {
province = jsonReader.nextString();
} else if ("phoneNum".equals(key)) {
phoneNum = jsonReader.nextString();
} else if ("address".equals(key)) {
address = jsonReader.nextString();
}
}
jsonReader.endObject();
return new PeopleEntry(id, name, age, province, phoneNum, address);
}

}

下面是以上代码的演示结果:
1,单个实体对象转换为JSON格式



2,带泛型的实体对象集合转换为为JSON(截图不完整)



3,单个JSONString转换为实体对象



4,集合型JSON转换为实体对象集合(截图不完整)



集合型JSON转换为实体对象集合(截图不完整),这是第二种方法



5,实体对象Map集合转换为Map集合型JSON(截图不完整)



6,Map集合型JSON转换为实体对象Map集合



再次附上完整Eclipse项目代码包免费下载链接: http://download.csdn.net/detail/zjluocisoftstone/9446205

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java GSON JSON