如何使用凌空读取JSON对象

时间:2018-08-13 12:40:30

标签: android json gson android-volley

在我拥有的json链接中,它包含一个名为products的属性,它是一个包含多个对象的数组。如何读取该属性products并遍历其中的每个元素?例如,如何获取id,颜色和价格的值?我尝试了以下操作,但似乎这行

Response.Listener<JSONObject> onPostsLoaded

不接受JSONObject作为类型

请让我知道如何使用凌空读取json对象

 private void initGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("M/d/yy hh:mm a");
    gson = gsonBuilder.create();
}

private void doRetrofit() {
    API_BASE_URL = this.getResources().getString(R.string.BASE_URL);
    requestQueue = Volley.newRequestQueue(this);
    fetchPosts();
}

private void fetchPosts() {
    StringRequest request = new StringRequest(Request.Method.GET, API_BASE_URL, onPostsLoaded, onPostsError);
    requestQueue.add(request);
}

private final Response.Listener<JSONObject> onPostsLoaded = new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(String response) {
        Log.i(TAG, response);

        response.getJs
        //List<Repo> repos = Arrays.asList(gson.fromJson(response, Repo[].class));

        /*Log.i("PostActivity", repos.size() + " posts loaded.");
        for (Repo repo : repos) {
            //Log.i("PostActivity", repo.getImageUrl() + ": " + repo.getName());
        }*/
    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, error.toString());
    }
};

JSON

 products: [
 {
     name: "Yellow Triangle",
     type: "Triangle",
     id: 1,
     color: "Yellow",
     imageURL: "https://kredit.check24.de/konto- 
     kredit/ratenkredit/nativeapps/imgs/08.png",
     colorCode: "FFECB3",
     available: true,
     releaseDate: 1460629605,
     description: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, 
sed diam",
     longDescription: "Lorem ipsum dolor sit amet, consetetur sadipscing 
elitr, sed diam Lorem ipsum dolor sit amet, consetetur sadipscing 
elitr, sed diam Lorem ipsum dolor sit amet, consetetur sadipscing 
elitr, sed diam Lorem ipsum dolor sit amet, consetetur sadipscing 
elitr, sed diam",
     rating: 2.17,
     price: {
         value: 225.91,
         currency: "EUR"
         }
    },

3 个答案:

答案 0 :(得分:0)

您应该start with the documentation。您可以使用IDE为您提取那些侦听器,而不是手动拉出侦听器。

监听器的类型是响应的内容。

您告诉它使用JSON对象响应,但是该方法未实现正确的签名

这应该编译

 Event::listen('cms.page.display', function ($controller, $url, $page, $result) {
        $headers = [
            'Cache-Control' => 'max-age=2592000, public',
        ];
        return Response::make($result, $controller->getStatusCode(), $headers);
    });

由于您有Gson,see it's usage in the documentation with Volley

答案 1 :(得分:0)

您选择了错误的数据类型。如下更改您的代码:

private void fetchPosts() {
    StringRequest request = new StringRequest(Request.Method.GET, API_BASE_URL, onPostsLoaded, onPostsError);
    requestQueue.add(request);
}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        JSONObject obj = new JSONObject(response);

        // use obj to get your data
    }
};

当有Response.Listener<JSONObject>时,您会有一个JSONObject作为响应:

Response.Listener<String>     ----->    public void onResponse(String response)
Response.Listener<JSONObject> ----->    public void onResponse(JSONObject response)

答案 2 :(得分:0)

尝试:

      Volley.newRequestQueue(getActivity()).add(new StringRequest(Request.Method.GET,"api_link", new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            JSONObject mJsonObject;

            try {
                JSONArray mJsonArray=new JSONArray(s)
                JSONArray mJsonArray1 = mJsonArray.getJSONArray("products");
                int a = mJsonArray1.length();
                for (int i = 0; i < a; i++) {
                    JSONObject jo = mJsonArray1.getJSONObject(i);
                    homeModel.setID(jo.getString("color"));
                    //AND add somthing code u want

                }
            } catch (JSONException e) {
                Toast.makeText(getActivity(), "Exception", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

我的HomeModel列表:

 public class HomeModel {
public String ID;
public String pic;
public String color;

public String getcolor() {
    return color;
}

 public String setcolor(String color) {
   this.color=String color
   }

 }