Android的Gson的使用方法,实现Json结构间相互转换

一,把数组,对象,List,Map等数据结构转换成Json字符串

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Main {

	public static class Student{
		    private String name;
		    int age;
		    private String address;

		    private Date dateOfBirth;
		    public Student() {
		    }
		    public Student(String name ,int age,String address, Date dateOfBirth) {
		        this.name = name;
		        this.age=age;
		        this.address = address;
		        this.dateOfBirth = dateOfBirth;
		    }

		    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 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;
		    }
	}
	public static void main(String[] args) {
		 Gson gson=new Gson();

		/*数组转化成Json串*/
		 int[] numbers = {1, 1, 2, 3, 5, 8, 13};
	     String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
	     String numbersJson=gson.toJson(numbers);
	      String daysJson = gson.toJson(days);
	      System.out.println("数组转化成Json字符串:");
	      System.out.println("numbersJson = " + numbersJson);
	      System.out.println("daysJson = " + daysJson);

	     /*List转换成Json串,元素是字符串*/
	     List<String> names = new ArrayList<String>();
	        names.add("Alice");
	        names.add("Bob");
	        names.add("Carol");
	        names.add("Mallory");
	     String jsonNames = gson.toJson(names);
	     System.out.println("List转换成Json串,元素是字符串");
	     System.out.println("jsonNames = " + jsonNames);   

	     /*List转换成Json串,元素是对象*/
	    Student a = new Student("Alice", 20,"Apple St", new Date(2000, 10, 1));
	    Student b = new Student("Bob", 23,"Banana St", null);
	    Student c = new Student("Carol",42, "Grape St", new Date(2000, 5, 21));
	    Student d = new Student("Mallory",24, "Mango St", null);

	    List<Student> students = new ArrayList<Student>();
	     students.add(a);
	     students.add(b);
	     students.add(c);
	     students.add(d);
	     String jsonStudents = gson.toJson(students);
	     System.out.println("List转换成Json串,元素是对象");
	     System.out.println("jsonStudents = " + jsonStudents);
	     // Converts JSON string into a collection of Student object.
	     Type type = new TypeToken<List<Student>>(){}.getType();
	     System.out.println("Json串转换成List,元素是对象");
	     List<Student> studentList = gson.fromJson(jsonStudents, type);

	     for (Student student : studentList) {
	            System.out.println("student.getName() = " + student.getName());
	     } 

	     /*Map转化成Json串,value是字符串*/
	     Map<String, String> colors = new HashMap<String, String>();
	        colors.put("BLACK", "#000000");
	        colors.put("RED", "#FF0000");
	        colors.put("GREEN", "#008000");
	        colors.put("BLUE", "#0000FF");
	        colors.put("YELLOW", "#FFFF00");
	        colors.put("WHITE", "#FFFFFF");

	        String jsonmap = gson.toJson(colors);
	        System.out.println("Map转化成Json串,value是字符串");
	        System.out.println("json = " + jsonmap);
	        // Convert JSON string back to Map.
	        Type type1 = new TypeToken<Map<String, String>>(){}.getType();
	        Map<String, String> map = gson.fromJson(jsonmap, type1);
	        System.out.println("Json串转换成Map,value是字符串");
	        for (String key : map.keySet()) {
	            System.out.println("map.get = " + map.get(key));
	        }

	     /*Map转化成Json串,value是对象*/
	     Map<String, Student> studentmap = new HashMap<String, Student>();
	        studentmap.put("Alice", a);
	        studentmap.put("Bob", b);
	        studentmap.put("Carol", c);
	        studentmap.put("Mallory", d);

	        String jsonmap1 = gson.toJson(studentmap);
	        System.out.println("Map转化成Json串,value是对象");
	        System.out.println("json = " + jsonmap1);
	        // Convert JSON string back to Map.
	        Type type11 = new TypeToken<Map<String, Student>>(){}.getType();
	        System.out.println("Json串转换成Map,value是对象");
	        Map<String, Student> map1 = gson.fromJson(jsonmap1, type11);
	        for (String key : map1.keySet()) {
	            System.out.println("map1.get = " + map1.get(key).getName());
	        }   

	}

}

输出结果:

数组转化成Json字符串:
numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
List转换成Json串,元素是字符串
jsonNames = ["Alice","Bob","Carol","Mallory"]
List转换成Json串,元素是对象
jsonStudents = [{"name":"Alice","age":20,"address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","age":23,"address":"Banana St"},{"name":"Carol","age":42,"address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","age":24,"address":"Mango St"}]
Json串转换成List,元素是对象
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory
Map转化成Json串,value是字符串
json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
Json串转换成Map,value是字符串
map.get = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.get = #FF0000
Map转化成Json串,value是对象
json = {"Mallory":{"name":"Mallory","age":24,"address":"Mango St"},"Alice":{"name":"Alice","age":20,"address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},"Bob":{"name":"Bob","age":23,"address":"Banana St"},"Carol":{"name":"Carol","age":42,"address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"}}
Json串转换成Map,value是对象
map1.get = Mallory
map1.get = Alice
map1.get = Bob
map1.get = Carol

可以观察到:

1,单个对象Object,Json串是一个JsonObject,冒号“:”前面的key是java对象的变量名,冒号“:”后面的Value是java对象的变量值

2,数组和List,Json串是一个JsonArray

3,Map的Json串是一个JsonObject,冒号“:”前面的key是Map的Key值,冒号“:”后面的Value是Map的Value值

二,Json串转换成Java对象时,主要看冒号“:”后面的Value的数据类型是什么,这样Java对象的字段类型就是什么,可以说Value的数据类型和字段的数据类型是对应的

{
    "success":true,
    "data":
      {  "list":
              [{"dataType":0,
                "distance":435.2473470455821,
                "isFav":0,"parkCode":"0270000558",
                "parkName”:武汉金融港路场",
"parkID":558,
"remark":"",
"parkType":0,
"responsible":"",
"responseTel":"13297062676",
"consultTel":"",
"coordinateX":114.428102,
"coordinateY":30.462254,"
coordinateEntrance":"",
"rateInfo":"工作日",
"introduce":"",
"appState":3,
"paymentNoticeMinute":0,
"rentCount":0,
"rentSwitch":0,
"spaceCount":42,
"totalCount":42,
"imageName":"",
"fullImage":"",
"unitFee":0.0,
"unit":0,
"isRoadSide":0,
"rentOvertimeTimes":0.0,
"reservationKeepTime":0,
"supportPayType":0,
"address":"光谷大道金融港",
"state":1},

{"dataType":0,
"distance":568.3080108478586,
"isFav":0,
"parkCode":"0270000249",
"parkName":"武汉光谷金融港停车场",
"parkID":249,
"remark":"",
"parkType":3, "
“responsible":"",
"responseTel":"123456789",
"consultTel":"",
"coordinateX":114.427728,
"coordinateY":30.460922, "coordinateEntrance":"114.427005,30.461393,1,1;114.427863,30.462163,1,1;114.428469,30.462171,1,1;114.427885,30.461404,2,1;114.428514,30.461424,2,1;114.428851,30.461397,3,1,1;114.427351,30.462163,3,1,1;",
"rateInfo":"白天3元/小时\n晚上1元/小时",
"introduce":"",
"appState":15,
"paymentNoticeMinute":2,
"rentCount":0,
"rentSwitch":1,
"spaceCount":-95,
"totalCount":300,
"imageName":"7.jpg",
"fullImage":"/picture/park/249/7.jpg",
"unitFee":0.01,
"unit":20,
"isRoadSide":0,
"rentOvertimeTimes":0.0,
"reservationKeepTime":0,
"supportPayType":0,
"address":"武汉市光谷金融港\n武汉市光谷金融港B4座12层",
"state":1
}    ]
        }
}
package com.hust.map;

public class Park {

     int dataType;
     int rentCount;
     int parkCode;
     String parkName;	//停车场名字
     int parkID;
     String remark;
     int parkType;
     String responsible;
     String responseTel;
     String consultTel;
     double coordinateX;//经度
     double coordinateY;//纬度
     String coordinateEntrance;
     String rateInfo;	//收费标准
     String  introduce;
     int appState;
     int paymentNoticeMinute;
     int spaceCount;	//可租车位
     int totalCount;	//总车位
     String imageName;
     String fullImage;
     int reservationKeepTime;
     int isRoadSide;
     double rentOvertimeTimes;
     double unitFee;
     int unit;
     int rentSwitch;
     int supportPayType;
     int isFav;
     double distance;		//距离
     String address;	//地址
     int state;

	public double getCoordinateX() {
		return coordinateX;
	}
	public void setCoordinateX(double coordinateX) {
		this.coordinateX = coordinateX;
	}
	public double getCoordinateY() {
		return coordinateY;
	}
	public void setCoordinateY(double coordinateY) {
		this.coordinateY = coordinateY;
	}
	public String getParkName() {
		return parkName;
	}
	public void setParkName(String parkName) {
		this.parkName = parkName;
	}
	public int getSpaceCount() {
		return spaceCount;
	}
	public void setSpaceCount(int spaceCount) {
		this.spaceCount = spaceCount;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public String getRateInfo() {
		return rateInfo;
	}
	public void setRateInfo(String rateInfo) {
		this.rateInfo = rateInfo;
	}
	public double getDistance() {
		return distance;
	}
	public void setDistance(double distance) {
		this.distance = distance;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Park(int dataType, int rentCount, int parkCode, String parkName,
			int parkID, String remark, int parkType, String responsible,
			String responseTel, String consultTel, double coordinateX,
			double coordinateY, String coordinateEntrance, String rateInfo,
			String introduce, int appState, int paymentNoticeMinute,
			int spaceCount, int totalCount, String imageName, String fullImage,
			int reservationKeepTime, int isRoadSide, double rentOvertimeTimes,
			double unitFee, int unit, int rentSwitch, int supportPayType,
			int isFav, double distance, String address, int state) {
		super();
		this.dataType = dataType;
		this.rentCount = rentCount;
		this.parkCode = parkCode;
		this.parkName = parkName;
		this.parkID = parkID;
		this.remark = remark;
		this.parkType = parkType;
		this.responsible = responsible;
		this.responseTel = responseTel;
		this.consultTel = consultTel;
		this.coordinateX = coordinateX;
		this.coordinateY = coordinateY;
		this.coordinateEntrance = coordinateEntrance;
		this.rateInfo = rateInfo;
		this.introduce = introduce;
		this.appState = appState;
		this.paymentNoticeMinute = paymentNoticeMinute;
		this.spaceCount = spaceCount;
		this.totalCount = totalCount;
		this.imageName = imageName;
		this.fullImage = fullImage;
		this.reservationKeepTime = reservationKeepTime;
		this.isRoadSide = isRoadSide;
		this.rentOvertimeTimes = rentOvertimeTimes;
		this.unitFee = unitFee;
		this.unit = unit;
		this.rentSwitch = rentSwitch;
		this.supportPayType = supportPayType;
		this.isFav = isFav;
		this.distance = distance;
		this.address = address;
		this.state = state;
	}
	public int getDataType() {
		return dataType;
	}
	public void setDataType(int dataType) {
		this.dataType = dataType;
	}
	public int getRentCount() {
		return rentCount;
	}
	public void setRentCount(int rentCount) {
		this.rentCount = rentCount;
	}
	public int getParkCode() {
		return parkCode;
	}
	public void setParkCode(int parkCode) {
		this.parkCode = parkCode;
	}
	public int getParkID() {
		return parkID;
	}
	public void setParkID(int parkID) {
		this.parkID = parkID;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public int getParkType() {
		return parkType;
	}
	public void setParkType(int parkType) {
		this.parkType = parkType;
	}
	public String getResponsible() {
		return responsible;
	}
	public void setResponsible(String responsible) {
		this.responsible = responsible;
	}
	public String getResponseTel() {
		return responseTel;
	}
	public void setResponseTel(String responseTel) {
		this.responseTel = responseTel;
	}
	public String getConsultTel() {
		return consultTel;
	}
	public void setConsultTel(String consultTel) {
		this.consultTel = consultTel;
	}
	public String getCoordinateEntrance() {
		return coordinateEntrance;
	}
	public void setCoordinateEntrance(String coordinateEntrance) {
		this.coordinateEntrance = coordinateEntrance;
	}
	public String getIntroduce() {
		return introduce;
	}
	public void setIntroduce(String introduce) {
		this.introduce = introduce;
	}
	public int getAppState() {
		return appState;
	}
	public void setAppState(int appState) {
		this.appState = appState;
	}
	public int getPaymentNoticeMinute() {
		return paymentNoticeMinute;
	}
	public void setPaymentNoticeMinute(int paymentNoticeMinute) {
		this.paymentNoticeMinute = paymentNoticeMinute;
	}
	public String getImageName() {
		return imageName;
	}
	public void setImageName(String imageName) {
		this.imageName = imageName;
	}
	public String getFullImage() {
		return fullImage;
	}
	public void setFullImage(String fullImage) {
		this.fullImage = fullImage;
	}
	public int getReservationKeepTime() {
		return reservationKeepTime;
	}
	public void setReservationKeepTime(int reservationKeepTime) {
		this.reservationKeepTime = reservationKeepTime;
	}
	public int getIsRoadSide() {
		return isRoadSide;
	}
	public void setIsRoadSide(int isRoadSide) {
		this.isRoadSide = isRoadSide;
	}
	public double getRentOvertimeTimes() {
		return rentOvertimeTimes;
	}
	public void setRentOvertimeTimes(double rentOvertimeTimes) {
		this.rentOvertimeTimes = rentOvertimeTimes;
	}
	public double getUnitFee() {
		return unitFee;
	}
	public void setUnitFee(double unitFee) {
		this.unitFee = unitFee;
	}
	public int getUnit() {
		return unit;
	}
	public void setUnit(int unit) {
		this.unit = unit;
	}
	public int getRentSwitch() {
		return rentSwitch;
	}
	public void setRentSwitch(int rentSwitch) {
		this.rentSwitch = rentSwitch;
	}
	public int getSupportPayType() {
		return supportPayType;
	}
	public void setSupportPayType(int supportPayType) {
		this.supportPayType = supportPayType;
	}
	public int getIsFav() {
		return isFav;
	}
	public void setIsFav(int isFav) {
		this.isFav = isFav;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}

}

DataFromNetwork.java

package com.hust.map;

import java.util.ArrayList;
import java.util.HashMap;
public class DataFromNetWork {
      boolean success;
      HashMap<String,ArrayList<Park>> data;
}
DataFromNetWork mDataFromNetWork=mGson.fromJson(mParksString, DataFromNetWork.class);
	 ArrayList<Park> mParksList=mDataFromNetWork.data.get("list");
时间: 2024-10-13 15:13:21

Android的Gson的使用方法,实现Json结构间相互转换的相关文章

Google Gson的使用方法,实现Json结构的相互转换

在Java开发中,有时需要保存一个数据结构成字符串,可能你会考虑用Json,但是当Json字符串转换成Java对象时,转换成的是JsonObject,并不是你想要的Class类型的对象,操作起来就很不是愉悦,下面说的就可以解决了这种问题. 首先,需要把Google的Gson的Jar包导入到项目中,这个导入包的简单步骤就不展示了,Gson的下载链接:http://download.csdn.net/detail/qxs965266509/8367275 现在,我先自定义一个Class类 [java

Android利用Gson解析嵌套多层的Json

原文链接:http://www.cnblogs.com/jxgxy/p/3677256.html 补充说明:1.在我使用Gson的时候,内部类不是static的也是可以正确解析的 首先先讲一个比较简单点的例子(最简单的我就不讲啦,网上很多),帮助新手理解Gson的使用方法:                 比如我们要解析一个下面这种的Json:                 String json = {"a":"100","b":[{&quo

android 使用gson 处理Json

Json是一种类似于XML的通用数据交换格式,比XML传输效率高.更利于网络传输数据.这里说一些使用Gosn类来处理json数据.Gson比传统的json处理方式更加快速,Gson开源的.如果有兴趣的也可以了解一下阿里开发的fastgson,速度也非常快. 使用Gosn 处理json非常简单.第一我们首先创建一个JavaBean类 (1)创建User.java public class User { public User(String name, int age) { this.name =

Android原生方式解析Json,Gson三方框架方式解析Json

package com.example.administrator.test.Fragment.Login; import android.support.v4.media.VolumeProviderCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import c

Android与服务器通信的方法之一(json)效率不高安全性不好

http通信,以xml或者json为载体,相互通信数据. Android对于http的网络通信,提供了标准的java接口--httpURLConnection接口,以及apache的接口--httpclient接口.其中我自己用的比较多的而是httpclient这个接口,因为它的功能更为丰富很有效. 同时http通信也分为post方式和get的方式,两个相比较的话,post传送的数据量比较大,安全性也比较高.因此在做数据查询时,我会用get方式:而在做数据添加.修改或删除时,我就用Post方式

Android以JSONOject和GSON两种方式解析json

json文件如下: 将获取到的json数据转化为String形式 OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://10.0.2.2/get_data.json") .build(); Response response =client.newCall(request).execute(); String responseData = respon

Gson的使用方法

Gson是一种对象的解析json,很好用,介绍一个网站http://json.parser.online.fr/可以帮我们看一个字符串是不是Json 对于Json文件 { "id" : "3232", "data" : { "data1" : { "name" : "xiaoming", "age" : "12" } } } 如果用Gson来解析的

Gson中fromJson方法的返回值

Gson是google的一个Json库,使用非常简单.在Java中,只要引入包,创建对象就可以用了. fromJson是Gson提供的一个方法.用来将一个Json数据转换为对象.调用方法是:new Gson().fromJson(Json_string,class) 需要注意的是,它会“尽量”转换出对象,哪怕得到的对象从数据上看是不完整的. 这样,可以通过一个Json数据转换出多种类型的对象,完全看使用者的需求.当用XSLT格式化XML文件时也是这种思路. 需要注意的是,在调用fromJson时

Gson把对象转成json格式的字符串

最近在做一个java web service项目,需要用到jason,本人对java不是特别精通,于是开始搜索一些java平台的json类库. 发现了google的gson,因为之前对于protocolbuf有一些了解,带着一些好奇心,我开始使用了gson. 经过比较,gson和其他现有java json类库最大的不同时gson需要序列化得实体类不需要使用annotation来标识需要序列化得字段,同时gson又可以通过使用annotation来灵活配置需要序列化的字段. 下面是一个简单的例子: