如何使用Retrofit检索JSON的项目特定字段

时间:2018-02-14 22:44:16

标签: android json retrofit retrofit2

这是我得到的以下json对象:

{ "1":"data", "2":"data", "3":"data", "4":"data"}

数据是从传感器接收的int。 1,2,3和4是不同的传感器值。

我的Api班:

public interface DetailsAPI {
@GET("/SET/team1/retrieve_data")
Call<ResponseBody> getpost();
}

我的主要课程我称之为:

Retrofit retrofit = new Retrofit.Builder().baseUrl(ip.ip).build();

    final DetailsAPI api = retrofit.create(DetailsAPI.class);
    final Handler handler=new Handler();
    handler.post(new Runnable(){
        @Override
        public void run() {
            api.getpost().enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {

                        String res = response.body().string();
                        sensor1.setText(res);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
            // upadte textView here
            handler.postDelayed(this,100); // set time here to refresh textView
        }
    });

当它被打印时,我得到:

{ "1":"data", "2":"data", "3":"data", "4":"data"}

我希望能够指定1,2,3和4没有{“”:“”}

我想要的输出就像是

Light : data
Sound : data
Temp : data

4 个答案:

答案 0 :(得分:2)

您需要添加GSON Convertor才能进行改造。

创建一个这样的类

class Data{
    String key;
    String value;
}

使你的界面像这样

@GET("group/{id}/users") Call<List<Data>> groupList(@Path("id") int groupId);

您的改装回调

Retrofit retrofit = new Retrofit.Builder().baseUrl(ip.ip).build();
final DetailsAPI api = retrofit.create(DetailsAPI.class);
final Handler handler=new Handler();
handler.post(new Runnable(){ @Override public void run() { 
api.getpost().enqueue(new Callback<List<Data>>() { 
@Override public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {
 try { List<Data> res = response.body()
// after this us can use this list to iterate over.
 }
 catch (IOException e) { e.printStackTrace(); } } 
@Override public void onFailure(Call<List<Data>> call, Throwable t) { } }); // upadte textView here handler.postDelayed(this,100); // set time here to refresh textView } });

答案 1 :(得分:1)

因此,您的调用声明将ResponseBody对象作为响应。您可以创建自己的响应类并替换ResponseBody。

你可以在这里找到一些电话: http://square.github.io/retrofit/

看起来像:

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

它也会影响回调,你会把你的课作为回应。

答案 2 :(得分:1)

将gson-converter添加到您的项目中并将您的pojo类创建为:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class SensorData{

@SerializedName("1")
@Expose
private String sensor1;
@SerializedName("2")
@Expose
private String sensor2;
@SerializedName("3")
@Expose
private String sensor3;
@SerializedName("4")
@Expose
private String sensor4;

public String getSensor1() {
return sensor1;
}

public void setSensor1(String sensor1) {
this.sensor1= sensor1;
}

public String getSensor2() {
return sensor2;
}

public void setSensor2(String sensor2) {
this.sensor2= sensor2;
}

public String getSensor3() {
return sensor3;
}

public void setSensor3(String sensor3) {
this.sensor3= sensor3;
}

public String getSensor4() {
return sensor4;
}

public void setSensor4(String sensor4) {
this.sensor4= sensor4;
}

}

API类:

public interface DetailsAPI {
@GET("/SET/team1/retrieve_data")
Call<SensorData> getPost();
}

改装回调设置为:

Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(url)
                        .client(httpClient)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

DetailsAPI api = retrofit.create(DetailsAPI.class);
api.getPost().enqueue(new Callback<SensorData>() {
        @Override
        public void onResponse(Call<SensorData> call, 
        Response<SensorData> response) {
            Log.d(TAG, "onResponse: ");
            SensorData sensorData = response.body();
            System.out.println("Light :"+sensorData.getSensor1());
            System.out.println("Sound :"+sensorData.getSensor2());
            System.out.println("Temp :"+sensorData.getSensor3());
            System.out.println("Fire :"+sensorData.getSensor4());
        }

        @Override
        public void onFailure(Call<SensorData> call, Throwable t) {
            Log.d(TAG, "onFailure: ");
        }
    });

答案 3 :(得分:0)

像这样更改响应的模型类

public class ResponseBody {

@SerializedName("1")
@Expose
private String _1;
@SerializedName("2")
@Expose
private String _2;
@SerializedName("3")
@Expose
private String _3;
@SerializedName("4")
@Expose
private String _4;

public String get1() {
return _1;
}

public void set1(String _1) {
this._1 = _1;
}

public String get2() {
return _2;
}

public void set2(String _2) {
this._2 = _2;
}

public String get3() {
return _3;
}

public void set3(String _3) {
this._3 = _3;
}

public String get4() {
return _4;
}

public void set4(String _4) {
this._4 = _4;
}
}

然后改变你的改造onResponse内容,如

    try {

             ResponseBody res = response.body().string();
             sensor1.setText("Light :"+res.get1());
             sensor2.setText("Sound :"+res.get2()); //create textview sensor2
             sensor3.setText("Temp :"+res.get3()); //create textview sensor3
             } catch (IOException e) {
                    e.printStackTrace();
        }