Android获取服务器返回的JSON数据类型有以下几种方式:
方式一:使用Android自带的JSONObject和JSONArray解析JSON数据,代码如下:
String jsonString = "{'name':'Tom','age':18,'address':{'city':'Beijing','road':'No.11'}}";
try {
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
JSONObject addressObject = jsonObject.getJSONObject("address");
String city = addressObject.getString("city");
String road = addressObject.getString("road");
Log.d("JSON", "name:" + name + ",age:" + age + ",city:" + city + ",road:" + road);
} catch (JSONException e) {
e.printStackTrace();
}
方式二:使用第三方库Gson解析JSON数据,代码如下:
String jsonString = "{'name':'Tom','age':18,'address':{'city':'Beijing','road':'No.11'}}";
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
Log.d("Gson", person.toString());
其中Person类的定义如下:
public class Person {
private String name;
private int age;
private Address address;
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 Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "name:" + name + ",age:" + age + ",address:" + address.toString();
}
}
public class Address {
private String city;
private String road;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRoad() {
return road;
}
public void setRoad(String road) {
this.road = road;
}
@Override
public String toString() {
return "city:" + city + ",road:" + road;
}
}
方式三:使用RxJava和Retrofit结合解析JSON数据,代码如下:
public interface ApiService {
@GET("api")
Observable<Person> getPerson();
}
public class RetrofitManager {
private static final String HOST = "http://xxx.xxx.xxx.xxx/";
private ApiService apiService;
private RetrofitManager() {
OkHttpClient httpClient = new OkHttpClient.Builder().build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(HOST)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.build();
apiService = retrofit.create(ApiService.class);
}
public static RetrofitManager getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final RetrofitManager INSTANCE = new RetrofitManager();
}
public Observable<Person> getPerson() {
return apiService.getPerson();
}
}
RetrofitManager.getInstance().getPerson()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Person>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Person person) {
Log.d("Retrofit", person.toString());
}
});
需要注意的是:第三种方式需要引入RxJava和Retrofit的依赖库。
Android获取服务器json数据类型可以使用HttpURLConnection或者OkHttp,再利用JSON.parseObject()方法将JSON字符串转化为Java对象。
使用HttpURLConnection获取JSON数据:
public String httpURLConnectionMethod(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
String result = convertStreamToString(conn.getInputStream()); //转换输入流为 String
return result;
}
private String convertStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
return sb.toString();
}
使用OkHttp获取JSON数据:
public String okHttpMethod(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
String result = response.body().string();
return result;
}
将获取到的JSON数据转换为Java对象:
String jsonStr = httpURLConnectionMethod(urlString);
User user = JSON.parseObject(jsonStr, User.class);
以上代码中的 User 类是你定义的 Java 对象类,可以根据 JSON 数据的结构来定义。例如,如果 JSON 数据的结构如下:

{
"name": "Mike",
"age": 22,
"gender": "male"
}
则可以定义如下的 User 类:
public class User {
private String name;
private int age;
private String gender;
// getter and setter methods here
}
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/158280.html