Android - 如何从改造中获得 json

Android - how to get json from retrofit

我是 Retrofit 的新手,

 [
  {
    "scheme_name": "DSP BlackRock Tax Saver Fund (G)",
    "sch_id": "401",
    "scheme_code": "D110",
    "category_type": "Equity",
    "trxntype": "Lumpsum",
    "current_value": 570.178,
    "folio_no": "3417548/62",
    "units": 14.941,
    "trnx_date": "10-06-16",
    "current_invest": 500,
    "gainLoss": 70.18
  },
  {
    "scheme_name": "DSP BlackRock World Mining Fund  (G)",
    "sch_id": "1278",
    "scheme_code": "D341",
    "category_type": "Equity",
    "trxntype": "Lumpsum",
    "current_value": 1999.393,
    "folio_no": "3417548/62",
    "units": 302.16,
    "trnx_date": "21-07-16",
    "current_invest": 2000,
    "gainLoss": -0.61
  },
  {
    "scheme_name": "ICICI Prudential Savings Fund (G)",
    "sch_id": "119",
    "scheme_code": "P1543",
    "category_type": "Debt",
    "trxntype": "Full Redemption",
    "current_value": 0,
    "folio_no": "8349201/28",
    "units": 0,
    "trnx_date": "19-07-16",
    "current_invest": 0,
    "gainLoss": 0
  },
  {
    "scheme_name": "Kotak Emerging Equity Scheme (G)",
    "sch_id": "1001",
    "scheme_code": "K123",
    "category_type": "Equity",
    "trxntype": "Lumpsum",
    "current_value": 10309.489,
    "folio_no": "3625427/38",
    "units": 325.796,
    "trnx_date": "03-08-16",
    "current_invest": 10000,
    "gainLoss": 309.49
  }
]

这是json是get,

 package info.androidhive.retrofit.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import javax.annotation.Generated;

@Generated("org.jsonschema2pojo")
public class MyTransaction {

    @SerializedName("scheme_name")
    @Expose
    private String schemeName;
    @SerializedName("sch_id")
    @Expose
    private String schId;
    @SerializedName("scheme_code")
    @Expose
    private String schemeCode;
    @SerializedName("category_type")
    @Expose
    private String categoryType;
    @SerializedName("trxntype")
    @Expose
    private String trxntype;
    @SerializedName("current_value")
    @Expose
    private Float currentValue;
    @SerializedName("folio_no")
    @Expose
    private String folioNo;
    @SerializedName("units")
    @Expose
    private Float units;
    @SerializedName("trnx_date")
    @Expose
    private String trnxDate;
    @SerializedName("current_invest")
    @Expose
    private Integer currentInvest;
    @SerializedName("gainLoss")
    @Expose
    private Float gainLoss;



    public MyTransaction(String schemeName, String schId, String schemeCode, String categoryType, String trxntype, Float currentValue, String folioNo, Float units, String trnxDate, Integer currentInvest, Float gainLoss) {
        this.schemeName = schemeName;
        this.schId = schId;
        this.schemeCode = schemeCode;
        this.categoryType = categoryType;
        this.trxntype = trxntype;
        this.currentValue = currentValue;
        this.folioNo = folioNo;
        this.units = units;
        this.trnxDate = trnxDate;
        this.currentInvest = currentInvest;
        this.gainLoss = gainLoss;
    }



    /**
     *
     * @return
     * The schemeName
     */
    public String getSchemeName() {
        return schemeName;
    }

    /**
     *
     * @param schemeName
     * The scheme_name
     */
    public void setSchemeName(String schemeName) {
        this.schemeName = schemeName;
    }

    /**
     *
     * @return
     * The schId
     */
    public String getSchId() {
        return schId;
    }

    /**
     *
     * @param schId
     * The sch_id
     */
    public void setSchId(String schId) {
        this.schId = schId;
    }

    /**
     *
     * @return
     * The schemeCode
     */
    public String getSchemeCode() {
        return schemeCode;
    }

    /**
     *
     * @param schemeCode
     * The scheme_code
     */
    public void setSchemeCode(String schemeCode) {
        this.schemeCode = schemeCode;
    }

    /**
     *
     * @return
     * The categoryType
     */
    public String getCategoryType() {
        return categoryType;
    }

    /**
     *
     * @param categoryType
     * The category_type
     */
    public void setCategoryType(String categoryType) {
        this.categoryType = categoryType;
    }

    /**
     *
     * @return
     * The trxntype
     */
    public String getTrxntype() {
        return trxntype;
    }

    /**
     *
     * @param trxntype
     * The trxntype
     */
    public void setTrxntype(String trxntype) {
        this.trxntype = trxntype;
    }

    /**
     *
     * @return
     * The currentValue
     */
    public Float getCurrentValue() {
        return currentValue;
    }

    /**
     *
     * @param currentValue
     * The current_value
     */
    public void setCurrentValue(Float currentValue) {
        this.currentValue = currentValue;
    }

    /**
     *
     * @return
     * The folioNo
     */
    public String getFolioNo() {
        return folioNo;
    }

    /**
     *
     * @param folioNo
     * The folio_no
     */
    public void setFolioNo(String folioNo) {
        this.folioNo = folioNo;
    }

    /**
     *
     * @return
     * The units
     */
    public Float getUnits() {
        return units;
    }

    /**
     *
     * @param units
     * The units
     */
    public void setUnits(Float units) {
        this.units = units;
    }

    /**
     *
     * @return
     * The trnxDate
     */
    public String getTrnxDate() {
        return trnxDate;
    }

    /**
     *
     * @param trnxDate
     * The trnx_date
     */
    public void setTrnxDate(String trnxDate) {
        this.trnxDate = trnxDate;
    }

    /**
     *
     * @return
     * The currentInvest
     */
    public Integer getCurrentInvest() {
        return currentInvest;
    }

    /**
     *
     * @param currentInvest
     * The current_invest
     */
    public void setCurrentInvest(Integer currentInvest) {
        this.currentInvest = currentInvest;
    }

    /**
     *
     * @return
     * The gainLoss
     */
    public Float getGainLoss() {
        return gainLoss;
    }

    /**
     *
     * @param gainLoss
     * The gainLoss
     */
    public void setGainLoss(Float gainLoss) {
        this.gainLoss = gainLoss;
    }

}

以上为模型class。 Api 客户端代码

    public static final String BASE_URL = "http://www.mysiponline.com/admin-panel/AndroidApi/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

AIP接口代码

     @POST("client_trans/{user_id}")
    Call<MyTransaction> getTransaction(@Path("user_id") String id);

MainActivity 代码

    Call<MyTransaction> myTransactionCall = apiService.getTransaction("420");
        myTransactionCall.enqueue(new Callback<MyTransaction>() {
            @Override
            public void onResponse(Call<MyTransaction> call, Response<MyTransaction> response) {

                Log.e(TAG, "Partners list : response.body());
            }

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

            }
        });

mainActivity 代码出错。我无法得到它。请帮助并提前致谢。

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at info.androidhive.retrofit.activity.MainActivity.onResponse(MainActivity.java:65)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

您正在调用单个对象,但服务器返回给您对象列表。

@POST("client_trans/{user_id}")
    Call<List<MyTransaction>> getTransaction(@Path("user_id") String id);

也在这里编辑

 Call<List<MyTransaction>> myTransactionCall = apiService.getTransaction("420");
        myTransactionCall.enqueue(new Callback<List<MyTransaction>>() {
            @Override
            public void onResponse(Response<List<MyTransaction>> response) {
            if(response.code()!=200){
                  Log.d("Error",response.code()+"");
                  return;
               }
             for(MyTransaction data: response.body){
                  Log.d("Name",data.getSchemeName()+"");
                }
                Log.e(TAG, "Partners list : response.body());
            }

            @Override
            public void onFailure(Throwable t) {

            }
        });

这是解决方案。将AIP接口的代码改成这个

@FormUrlEncoded
@POST("client_trans")
Call<List<Example>> getTransaction(@Field("user_id") String user_id);

MainActivity 调用api函数的代码

Call<List<MyTransaction>> listCall = apiService.getTransaction("420");
    listCall.enqueue(new Callback<List<MyTransaction>>() {
        @Override
        public void onResponse(Call<List<MyTransaction>> call, Response<List<MyTransaction>> response) {

            List<MyTransaction> examples = response.body();

            Log.e(TAG, "Response : " + response.body());// Response : null
            for (int i = 0; i < examples.size(); i++) {
                Log.e(TAG, "examples list : " + examples.get(i).categoryType);
            }
        }

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

        }
    });

编码愉快。