android 解析数据之Gson

时间:2023-02-03 10:24:48

1、套路开始:先在android studio的setting中加入GsonFormat的插件

2、选好你要加载的Json数据

3、进入你需要加载的Json界面,将数据复制,并创建一个类

4、下载并且载入Gson的jar包,或者复制到libs中然后在build中加入一句话

compile 'com.google.code.gson:gson:2.8.0'

我这里创建的类名叫TvInfo(你可以根据实际情况取名),进入后(alt+s)GsonFormat快捷键,把你复制的数据粘贴到框内并自动生成代码即可

TvInfo

package com.chuanxidemo.shaoxin.demo09;

/**
* Created by shaoxin on 2017/2/25.
*/

public class TvInfo {

/**
* lon : 120.58531
* level : 2
* address :
* cityName :
* alevel : 4
* lat : 31.29888
*/

private double lon;
private int level;
private String address;
private String cityName;
private int alevel;
private double lat;

public double getLon() {
return lon;
}

public void setLon(double lon) {
this.lon = lon;
}

public int getLevel() {
return level;
}

public void setLevel(int level) {
this.level = level;
}

public String getAddress() {
return address;
}

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

public String getCityName() {
return cityName;
}

public void setCityName(String cityName) {
this.cityName = cityName;
}

public int getAlevel() {
return alevel;
}

public void setAlevel(int alevel) {
this.alevel = alevel;
}

public double getLat() {
return lat;
}

public void setLat(double lat) {
this.lat = lat;
}

@Override
public String toString() {
return "TvInfo{" +
"lon=" + lon +
", level=" + level +
", address='" + address + '\'' +
", cityName='" + cityName + '\'' +
", alevel=" + alevel +
", lat=" + lat +
'}';
}
}

4、创建Gson解析数据的基类

GsonUtil

package com.chuanxidemo.shaoxin.demo09;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
* Created by shaoxin on 2017/2/25.
*/

public class GsonUtil {
public static BufferedReader bufferedReader;
public static StringBuffer stringBuffer;

// 将Json数据解析成相应的映射对象
public static <T> T parseJsonWithGson(String jsonData, Class<T> type) {
Gson goson
= new Gson();
T result
= goson.fromJson(jsonData, type);
return result;
}

// 将Json数组解析成相应的映射对象列表
public static <T> List<T> parseJsonArrayWithGson(String jsonData, Class<T> cls) {
Gson gson
= new Gson();
List
<T> result = new ArrayList<>();
result
= gson.fromJson(jsonData, new TypeToken<List<T>>() {
}.getType());
return result;
}


// 根据json数据地址获取数据
public static String getData(String jsonURL) {
try {
stringBuffer
= new StringBuffer();
URL url
= new URL(jsonURL);//json地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(
"GET");//使用get方法接收
InputStream inputStream = connection.getInputStream();//得到一个输入流
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTf-8"));
String sread
= null;
while ((sread = bufferedReader.readLine()) != null) {
stringBuffer.append(sread);
stringBuffer.append(
"\r\n");
}
// Log.i("msg", "onClick: " + stringBuffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}


}

MainActivity

package com.chuanxidemo.shaoxin.demo09;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
GsonUtil gsonUtil;
private TextView txt;
private Button getData;
TvInfo tvInfo;
Handler handler;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt
= (TextView) findViewById(R.id.txt);
getData
= (Button) findViewById(R.id.get_data);

gsonUtil
= new GsonUtil();
handler
= new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
txt.setText(tvInfo.toString());
}
};
getData.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
super.run();
String data
= gsonUtil.getData("http://gc.ditu.aliyun.com/geocoding?a=%E8%8B%8F%E5%B7%9E%E5%B8%82");//加载的Json数据网址
tvInfo
= gsonUtil.parseJsonWithGson(data, TvInfo.class);
handler.sendEmptyMessage(
0x123);//线程中不能直接对UI进行设计所以用Handler解决
Log.i(
"msg", "run: " + tvInfo.getLon());

}
}.start();

}
});


}
}