【问题标题】:How to parse json data with retrofit on Android如何在 Android 上通过改造解析 json 数据
【发布时间】:2016-11-28 05:24:37
【问题描述】:

我会尝试在此处具体说明。所以我创建了最基本的代码来测试它,但我仍然无法获取数据,请帮忙!这是我的代码:

这是我本地服务器上的 json 输出: http://localhost:8080/KokosinjacRestfull/rest/textService/mudriPevci

[{"id":1,"subCategory":"MudriPevci","title":"Mujo i haso","description":"Krenuli do Grada","author":"luka","date":"2016-06-13"},{"id":3,"subCategory":"mudriPevci","title":"Perica","description" :“帕 on je napravio Haos","author":"luka","date":"2016-06-13"}]

文本类:

package kokosinjac.com.digiart.koktest.models;

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


public class Text {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("subCategory")
@Expose
private String subCategory;
@SerializedName("title")
@Expose
private String title;
@SerializedName("description")
@Expose
private String description;
@SerializedName("author")
@Expose
private String author;
@SerializedName("date")
@Expose
private String date;

/**
 * No args constructor for use in serialization
 *
 */


/**
 *
 * @param id
 * @param author
 * @param title
 * @param subCategory
 * @param description
 * @param date
 */


/**
 *
 * @return
 * The id
 */
public Integer getId() {
    return id;
}

/**
 *
 * @param id
 * The id
 */
public void setId(Integer id) {
    this.id = id;
}

/**
 *
 * @return
 * The subCategory
 */
public String getSubCategory() {
    return subCategory;
}

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

/**
 *
 * @return
 * The title
 */
public String getTitle() {
    return title;
}

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

/**
 *
 * @return
 * The description
 */
public String getDescription() {
    return description;
}

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

/**
 *
 * @return
 * The author
 */
public String getAuthor() {
    return author;
}

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

/**
 *
 * @return
 * The date
 */
public String getDate() {
    return date;
}

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

}

API 接口类:

包 kokosinjac.com.digiart.koktest.retrofit;

导入 java.util.ArrayList;

导入 kokosinjac.com.digiart.koktest.models.Text;进口 retrofit2.调用;导入改造2.http.GET;导入改造2.http.Path;

公共接口 RetrofitAPInterface {

@GET("rest/textService/{subCategory}")
Call<ArrayList<Text>> getText(@Path("subCategory") String subCat);

}

在手机上显示数据的类(你不需要注意一些字符串,只需看看改造部分,我已经尽可能简单了, subCatData.class:

public static final String BASE_URL ="http://localhost:8080/KokosinjacRestfull/";
HashMap<String,String> dataArr;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_sub_cat_data);
    final TextView tView = (TextView) findViewById(R.id.textView);
    Intent intent = getIntent();
    String urlSecondPartBefore = intent.getStringExtra("passedSubCat");
    String urlSecondPartAfter = urlSecondPartBefore.replaceAll("\\s", "");
    String urlFirstPart = intent.getStringExtra("passedUrlFirstPart");
    String catName = intent.getStringExtra("passedCatName");
    String data = null;
   // TextView test = (TextView) findViewById(R.id.test);


    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RetrofitAPInterface apiService = retrofit.create(RetrofitAPInterface.class);
    Call<ArrayList<Text>> call = apiService.getText("mudriPevci");
    call.enqueue(new Callback<ArrayList<Text>>() {
        @Override
        public void onResponse(Call<ArrayList<Text>> call, Response<ArrayList<Text>> response) {
            int statusCode = response.code();
            ArrayList<Text> textArray = response.body();
            for (Text t : textArray){
                tView.setText(t.getDescription());
            }
          //  Log.i("DATA", "onResponse: "+text.getId());
        }

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

        }
    });

}

}

我知道所有数据都将转到一个简单的 label ,但它是用于测试目的。我仍然无法检索任何内容,也没有收到任何错误。帮助将不胜感激。谢谢!

【问题讨论】:

标签: java android json retrofit


【解决方案1】:

我认为 你的 URL 有问题,如果你 用 android 模拟器测试你的应用程序,那么试试 "http://10.0.2.2:8080/" 但如果你是 用设备测试,那么您需要传递您的机器 IP 地址,例如 "http://192.143.1.0/" 并确保您的设备与您的数据库所在的机器连接。

【讨论】:

  • 我知道这个问题,因此我正在使用我的模拟器进行测试。代码看起来还可以吗?
  • 是的,您的代码看起来还可以,但是因为您在 URL 中使用 localhost 可能会出现问题,因此请尝试使用 "http://10.0.2.2:8080/" 而不是 localhost
  • 谢谢先生,它有效!我尝试直接在浏览器中测试它,但它在那里不起作用,只在 android studio 中。感谢您的帮助!
【解决方案2】:

要在 Android 上解析JSON 数据,我强烈建议您使用JSOUP,您可以通过单击here 找到它,它简单、直接且用户友好。非常容易学习。希望对您有所帮助!

【讨论】:

  • 谢谢你的回复,问题是因为我稍后会使用改造来上传数据,所以我想我需要像api一样的休息。谢谢
【解决方案3】:

问题可能出在您的 BASE_URL 将您的 BASE_URL 更改为 BASE_URL ="http://&lt;your_local_ip_address&gt;/KokosinjacRestfull/";

【讨论】:

  • 我知道这个问题,因此我正在使用我的模拟器进行测试。代码看起来还可以吗?
【解决方案4】:

我希望下面的例子可能会有所帮助

     public void startFetching() {
    mApiManager.getFlowerApi().getFlowers(new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            Log.d(TAG, "JSON :: " + s);

            try {
                JSONArray array = new JSONArray(s);

                for(int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);

                    Flower flower = new Flower.Builder()
                            .setCategory(object.getString("category"))
                            .setPrice(object.getDouble("price"))
                            .setInstructions(object.getString("instructions"))
                            .setPhoto(object.getString("photo"))
                            .setName(object.getString("name"))
                            .setProductId(object.getInt("productId"))
                            .build();

                    mListener.onFetchProgress(flower);

                }

            } catch (JSONException e) {
                mListener.onFetchFailed();
            }


            mListener.onFetchComplete();
        }

        @Override
        public void failure(RetrofitError error) {
            Log.d(TAG, "Error :: " + error.getMessage());
            mListener.onFetchComplete();
        }
    });
}

【讨论】:

    【解决方案5】:

    问题在于您的 URL Android 无法访问您的本地主机,即 http://localhost:8080/KokosinjacRestfull/rest/textService/mudriPevci

    在特定 IP 中启动您的服务器并运行。新 IP 就像 http://192.168.1.1/KokosinjacRestfull/rest/textService/mudriPevci

    【讨论】:

      【解决方案6】:

      使用 ip 地址代替 localhost(从 url 替换 localhost 并将您计算机的 ipaddress 放置为 ip 地址打开 cmd 并键入 ipconfig 并替换 localhost)。

      【讨论】:

        猜你喜欢
        • 2021-04-19
        • 1970-01-01
        • 2021-01-22
        • 2017-07-07
        • 2020-10-18
        • 2017-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多