可以也必须参考下面这篇文章的链接来学习json数据
目前解析json有三种工具:org.json(Java常用的解析),fastjson(阿里巴巴工程师开发的),Gson(Google官网出的),解析速度最快的是Gson,下载地址:https://code.google.com/p/google-gson/
什么是JSON:
JSON即JavaScript Object Natation, 它是一种轻量级的数据交换格式, 与XML一样, 是广泛被采用的客户端和服务端交互的解决方案.
JSON对象:
JSON中对象(Object)以"{"开始, 以"}"结束. 对象中的每一个item都是一个key-value对, 表现为"key:value"的形式, key-value对之间使用逗号分隔. 如:{"name":"coolxing", "age"=24, "male":true, "address":{"street":"huiLongGuan", "city":"beijing", "country":"china"}}. JSON对象的key只能是string类型的, 而value可以是string, number, false, true, null, Object对象甚至是array数组, 也就是说可以存在嵌套的情况.
JSON数组:
JSON数组(array)以"["开始, 以"]"结束, 数组中的每一个元素可以是string, number, false, true, null, Object对象甚至是array数组, 数组间的元素使用逗号分隔. 如["coolxing", 24, {"street":"huiLongGuan", "city":"beijing", "country":"china"}].
google的Gson使用
google的Gson封装的比较彻底,实现简单:
一、下载Gson的jar包:gson-2.2.4.jar
二、新建工程,导入jar包。
三、新建实体类:
package com.cn.entity;
public class User {
private String name;
private Integer age;
private String address;
public User(){
}
public User(String name, Integer age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
四、新建静态工具类实现Gson对象只实例化一次:
JsonToObject.java--->>>
package com.cn.util;
import com.google.gson.Gson;
public class JsonToObject {
private static final Gson googleJson = new Gson();
/**
* 获取Gson常量,减少重复创建,在编译后就完成改变量初始化
* @return
*/
public static Gson getGoogleJson(){
return googleJson;
}
/**
* 直接获取
* @param <T>
* @param json
* @param class1
* @return
*/
public static <T> Object jsonToObject(String json , Class<T> class1){
return googleJson.fromJson(json, class1);
}
}
ObjectToJsonUtil.java--->>>
package com.cn.util;
import com.google.gson.Gson;
public class ObjectToJsonUtil {
private static final Gson googleJson = new Gson();
/**
* 获取Gson常量,减少重复创建,在编译后就完成改变量初始化
* @return
*/
public static Gson getGoogleJson(){
return googleJson;
}
public static String objectToJson(Object object){
return googleJson.toJson(object);
}
}
五、建立测试类,进行测试:
package com.cn.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cn.entity.User;
import com.cn.util.JsonToObject;
import com.cn.util.ObjectToJsonUtil;
import com.google.gson.reflect.TypeToken;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
//对象转json字符串
User zhang = new User("zhang", 21, "深圳");
System.out.println("张某某转为json字符串:"+ObjectToJsonUtil.objectToJson(zhang));
//json转对象
String json = "{'name':'wang','age':23,'address':'北京'}";
User wang = (User)JsonToObject.jsonToObject(json, User.class);
System.out.println("json字符串转为王某某:"+"名字-"+wang.getName()+",年龄-"+wang.getAge()+",地址-"+wang.getAddress());
//字符串数组转json
String[] strs = {"中国","湖北","武汉"};
System.out.println(ObjectToJsonUtil.objectToJson(strs));
//list对象转json
List<User> list = new ArrayList<User>();
list.add(new User("张三", 21, "北京"));
list.add(new User("李四", 22, "上海"));
list.add(new User("王五", 23, "深圳"));
System.out.println(ObjectToJsonUtil.objectToJson(list));
//map对象转json
Map<String, User> map = new HashMap<String, User>();
map.put("第一名", new User("张三", 21, "北京"));
map.put("第二名", new User("李四", 22, "上海"));
map.put("第三名", new User("王五", 23, "深圳"));
System.out.println(ObjectToJsonUtil.objectToJson(map));
//json转list集合
String jsonList = "[{'name':'zhang','age':21,'address':'北京'},{'name':'wang','age':22,'address':'上海'},{'name':'zhao','age':23,'address':'深圳'}]";
List<User> personList = JsonToObject.getGoogleJson().fromJson(jsonList, new TypeToken<List<User>>(){}.getType());
System.out.println(personList.get(0).getName()+"---"+personList.get(1).getName()+"---"+personList.get(2).getName());
//json转map集合
String jsonMap = "{'one':{'name':'zhang','age':21,'address':'北京'},'two':{'name':'wang','age':22,'address':'上海'},'three':{'name':'zhao','age':23,'address':'深圳'}}";
Map<String, User> personMap = JsonToObject.getGoogleJson().fromJson(jsonMap, new TypeToken<Map<String , User>>(){}.getType());
System.out.println("第一名:"+personMap.get("one").getName()+" 第二名:"+personMap.get("two").getName()+" 第三名:"+personMap.get("three").getName());
}
}
总结:主要使用Gson对象的toJson实现对象序列化成json字符串 和fromJson实现把json字符串反序列化成对象。在把json转成List和Map集合的时候
使用TypeToken代理对象实现转换。
Gson的基本使用方法:
通过获取JsonReader对象解析JSON数据:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]"; try{ JsonReader reader = new JsonReader(new StringReader(jsonData)); reader.beginArray(); while(reader.hasNext()){ reader.beginObject(); while(reader.hasNext()){ String tagName = reader.nextName(); if(tagName.equals("username")){ System.out.println(reader.nextString()); } else if(tagName.equals("userId")){ System.out.println(reader.nextString()); } } reader.endObject(); } reader.endArray(); } catch(Exception e){ e.printStackTrace(); }
通过把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组进行操作:
创建JSON数据对应的一个POJO对象User.java:
public class User { private String username ; private int userId ; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } }
使用Gson对象获取User对象数据进行相应的操作:
Type listType = new TypeToken<LinkedList<User>>(){}.getType(); Gson gson = new Gson(); LinkedList<User> users = gson.fromJson(jsonData, listType); for (Iterator iterator = users.iterator(); iterator.hasNext();) { User user = (User) iterator.next(); System.out.println(user.getUsername()); System.out.println(user.getUserId()); }
如果要处理的JSON字符串只包含一个JSON对象,则可以直接使用fromJson获取一个User对象:
String jsonData = "{\"username\":\"arthinking\",\"userId\":001}"; Gson gson = new Gson(); User user = gson.fromJson(jsonData, User.class); System.out.println(user.getUsername()); System.out.println(user.getUserId());
解析复杂实例:
数据格式:
{
"data": {
"partnerteamlist": [
{
"pteamId": 72825,
"ptitle": "随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",
"pteamprice": 288
},
{
"pteamId": 72598,
"ptitle": "随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",
"pteamprice": 2888
},
{
"pteamId": 72613,
"ptitle": "随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",
"pteamprice": 3699
},
{
"pteamId": 72638,
"ptitle": "随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",
"pteamprice": 4299
},
{
"pteamId": 72716,
"ptitle": "随摄影/3组服装造型/内外景拍摄/完全透明消费!",
"pteamprice": 388
}
],
"liketeamlist": [
{
"lteamId": 65886,
"ltitle": "爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",
"limage": "http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",
"lteamprice": 518,
"lmarketprice": 3999
},
{
"lteamId": 57133,
"ltitle": "陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",
"limage": "http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",
"lteamprice": 580,
"lmarketprice": 3380
}
],
"feedbacks": {
"feedbacklist": [
{
"comment": "5分",
"createtime": "2014.07.08 13:38",
"score": 5,
"username": "l***2"
}
],
"totalcount": 1,
"totalscore": 5
}
},
"err": null,
"state": 1
}
实体类(里面的成员变量和接口的返回值名称一 一对应才能保证解析正确):
package com.pztuan.entity;
import java.util.List;
public class OtherDetail {
private int state;
private List<err> err;
private OtherDetail2 data;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public List<err> getErr() {
return err;
}
public void setErr(List<err> err) {
this.err = err;
}
public OtherDetail2 getData() {
return data;
}
public void setData(OtherDetail2 data) {
this.data = data;
}
public class OtherDetail2 {
private List<partnerteamlist> partnerteamlist;
private List<liketeamlist> liketeamlist;
private List<feedbacks> feedbacks;
public List<liketeamlist> getLiketeamlist() {
return liketeamlist;
}
public void setLiketeamlist(List<liketeamlist> liketeamlist) {
this.liketeamlist = liketeamlist;
}
public List<feedbacks> getFeedbacks() {
return feedbacks;
}
public void setFeedbacks(List<feedbacks> feedbacks) {
this.feedbacks = feedbacks;
}
public class partnerteamlist {
private int pteamId;
private String ptitle;
private Double pteamprice;
public int getPteamId() {
return pteamId;
}
public void setPteamId(int pteamId) {
this.pteamId = pteamId;
}
public String getPtitle() {
return ptitle;
}
public void setPtitle(String ptitle) {
this.ptitle = ptitle;
}
public Double getPteamprice() {
return pteamprice;
}
public void setPteamprice(Double pteamprice) {
this.pteamprice = pteamprice;
}
}
public class liketeamlist {
private int lteamId;
private String ltitle;
private String limage;
private Double lteamprice;
private Double lmarketprice;
public int getLteamId() {
return lteamId;
}
public void setLteamId(int lteamId) {
this.lteamId = lteamId;
}
public String getLtitle() {
return ltitle;
}
public void setLtitle(String ltitle) {
this.ltitle = ltitle;
}
public String getLimage() {
return limage;
}
public void setLimage(String limage) {
this.limage = limage;
}
public Double getLteamprice() {
return lteamprice;
}
public void setLteamprice(Double lteamprice) {
this.lteamprice = lteamprice;
}
public Double getLmarketprice() {
return lmarketprice;
}
public void setLmarketprice(Double lmarketprice) {
this.lmarketprice = lmarketprice;
}
}
public class feedbacks {
private int totalcount;
private Double totalscore;
private List<feedbacklist> feedbacklist;
public int getTotalcount() {
return totalcount;
}
public void setTotalcount(int totalcount) {
this.totalcount = totalcount;
}
public Double getTotalscore() {
return totalscore;
}
public void setTotalscore(Double totalscore) {
this.totalscore = totalscore;
}
public List<feedbacklist> getFeedbacklist() {
return feedbacklist;
}
public void setFeedbacklist(List<feedbacklist> feedbacklist) {
this.feedbacklist = feedbacklist;
}
public class feedbacklist {
private String username;
private String comment;
private String createtime;
private Double score;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
}
public List<partnerteamlist> getPartnerteamlist() {
return partnerteamlist;
}
public void setPartnerteamlist(List<partnerteamlist> partnerteamlist) {
this.partnerteamlist = partnerteamlist;
}
}
public class err {
private int code;
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
}
注意上面内部类的运用。
解析:
Gson gson = new Gson();
OtherDetail d = gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)
若出现引用异常,请查看Java内部类设计原则。
下面的例子中我们示例如何将一个数据转换成 json 串,并使用 Gson.toJson()
方法将数组序列化为 JSON,以及Gson.fromJson()
方法将 JSON 串反序列化为 java 数组。
import com.google.gson.Gson;
public class ArrayToJson {
public static void main(String[] args) {
int[] numbers = {1, 1, 2, 3, 5, 8, 13};
String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
//
// Create a new instance of Gson
//
Gson gson = new Gson();
//
// Convert numbers array into JSON string.
//
String numbersJson = gson.toJson(numbers);
//
// Convert strings array into JSON string
//
String daysJson = gson.toJson(days);
System.out.println("numbersJson = " + numbersJson);
System.out.println("daysJson = " + daysJson);
//
// Convert from JSON string to a primitive array of int.
//
int[] fibonacci = gson.fromJson(numbersJson, int[].class);
for (int i = 0; i < fibonacci.length; i++) {
System.out.print(fibonacci[i] + " ");
}
System.out.println("");
//
// Convert from JSON string to a string array.
//
String[] weekDays = gson.fromJson(daysJson, String[].class);
for (int i = 0; i < weekDays.length; i++) {
System.out.print(weekDays[i] + " ");
}
System.out.println("");
//
// Converting multidimensional array into JSON
//
int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
String json = gson.toJson(data);
System.out.println("Data = " + json);
//
// Convert JSON string into multidimensional array of int.
//
int[][] dataMap = gson.fromJson(json, int[][].class);
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println("");
}
}
}
以下是输出结果:
numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13
Sun Mon Tue Wed Thu Fri Sat
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3
3 4 5
如何将集合转化为 json 串?
下面的例子中我们示例如何将Java集合转换为符合 json 规则的字符串。
import java.util.Date;
public class Student {
private String name;
private String address;
private Date dateOfBirth;
public Student() {
}
public Student(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CollectionToJson {
public static void main(String[] args) {
//
// Converts a collection of string object into JSON string.
//
List<String> names = new ArrayList<String>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
names.add("Mallory");
Gson gson = new Gson();
String jsonNames = gson.toJson(names);
System.out.println("jsonNames = " + jsonNames);
//
// Converts a collection Student object into JSON string
//
Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));
Student b = new Student("Bob", "Banana St", null);
Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
Student d = new Student("Mallory", "Mango St", null);
List<Student> students = new ArrayList<Student>();
students.add(a);
students.add(b);
students.add(c);
students.add(d);
gson = new Gson();
String jsonStudents = gson.toJson(students);
System.out.println("jsonStudents = " + jsonStudents);
//
// Converts JSON string into a collection of Student object.
//
Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> studentList = gson.fromJson(jsonStudents, type);
for (Student student : studentList) {
System.out.println("student.getName() = " + student.getName());
}
}
}
以下是输出结果:
jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory
如何将Map转化为 json 串?
下面的例子中我们示例如何将java.util.Map
转化成 json 串,然后再将 json 串转换为java.util.Map
。
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class MapToJson {
public static void main(String[] args) {
Map<String, String> colours = new HashMap<String, String>();
colours.put("BLACK", "#000000");
colours.put("RED", "#FF0000");
colours.put("GREEN", "#008000");
colours.put("BLUE", "#0000FF");
colours.put("YELLOW", "#FFFF00");
colours.put("WHITE", "#FFFFFF");
//
// Convert a Map into JSON string.
//
Gson gson = new Gson();
String json = gson.toJson(colours);
System.out.println("json = " + json);
//
// Convert JSON string back to Map.
//
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map = gson.fromJson(json, type);
for (String key : map.keySet()) {
System.out.println("map.get = " + map.get(key));
}
}
}
以下是输出结果:
json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
map.get = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.get = #FF0000
如何将对象转换为 json 串?
下面的例子中我们示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串,并且实施起来也非常简单,你仅仅需要创建一个 Gson 实例,然后传递将被转化为 json 串的对象,并调用该实例的 toJson 方法即可。
import com.google.gson.Gson;
import java.util.Calendar;
public class StudentToJson {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(2000, 1, 1, 0, 0, 0);
Student student = new Student("Duke", "Menlo Park", dob.getTime());
Gson gson = new Gson();
String json = gson.toJson(student);
System.out.println("json = " + json);
}
}
import java.util.Date;
public class Student {
private String name;
private String address;
private Date dateOfBirth;
public Student() {
}
public Student(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
以下是输出结果:
json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
如何将 json 串转换为对象?
下面的例子中我们示例如何 json 串转化成 Java对象。
import com.google.gson.Gson;
public class JsonToStudent {
public static void main(String[] args) {
String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);
System.out.println("student.getName() = " + student.getName());
System.out.println("student.getAddress() = " + student.getAddress());
System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
}
}
以下是输出结果:
student.getName() = Duke
student.getAddress() = Menlo Park
student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000
如何处理对象的字段?
下面的例子中我们示例如何利用Gson处理一个对象的某一字段。
import com.google.gson.Gson;
import java.util.Calendar;
public class GsonFieldExample {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(1980, 10, 11);
People people = new People("John", "350 Banana St.", dob.getTime());
people.setSecret("This is a secret!");
Gson gson = new Gson();
String json = gson.toJson(people);
System.out.println("json = " + json);
}
}
import java.util.Date;
public class People {
private String name;
private String address;
private Date dateOfBirth;
private Integer age;
private transient String secret;
public People(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
以下是输出结果:
json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}
参考:http://www.itzhai.com/android-to-parse-json-data-using-gson.html