使用Volley通过URL进行JSON解析

时间:2018-11-16 08:30:05

标签: android json parsing android-volley

我试图使用截距来解析从URL接收到的JSON数据。但是它不能正常工作。我不明白jasonArray和jasonObject之间的区别。

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private ExampleAdapter mExampleAdapter;
    private ArrayList<ExampleItem> mExampleList;
    private RequestQueue mRequestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mExampleList = new ArrayList<>();

        mRequestQueue = Volley.newRequestQueue(this);
        parseJSON();
    }

    private void parseJSON() {
        String url = "http://api.visitkorea.or.kr/openapi/service/rest/KorService/locationBasedList?" +
        "serviceKey=gCoROJjTpFwTjV%2F%2BoWBcWMdj0z%2Fxsu22eY19j%2FoeNSJOnrkaPehhoyIzp%2FrtMkNYAzVlBFzmnI6cCsKODNmejA%3D%3D&" +
                "numOfRoews=10&pageNo=1&startPage=1&MobileOS=AND&MobileApp=WelcomeToSeoul&_type=json&arrange=A&contenTypeId=15&mapX=126.981611&mapY=37.568477&radius=1000&listYN=Y";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject parse_respone = response.getJSONObject("response");
                            JSONObject parse_body = parse_respone.getJSONObject("body");
                            JSONObject parse_items = parse_body.getJSONObject("items");
                            JSONArray jsonArray = parse_items.getJSONArray("item");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);

                                String creatorName = hit.getString("title");
                                String imageUrl = hit.getString("firstimage");
                                int likeCount = hit.getInt("siguncode");

                                mExampleList.add(new ExampleItem(imageUrl, creatorName, likeCount));
                            }

                            mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
                            mRecyclerView.setAdapter(mExampleAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);
    }
}

我从URL收到的数据:

{
"response": {
    "header": {
        "resultCode": "0000",
        "resultMsg": "OK"
    },
    "body": {
        "items": {
            "item": [
                {
                    "addr1": "서울특별시 중구 세종대로 110",
                    "areacode": 1,
                    "cat1": "A02",
                    "cat2": "A0207",
                    "cat3": "A02070200",
                    "contentid": 1742496,
                    "contenttypeid": 15,
                    "createdtime": 20121029114117,
                    "dist": 355,
                    "firstimage": "http://tong.visitkorea.or.kr/cms/resource/17/2560517_image2_1.jpg",
                    "firstimage2": "http://tong.visitkorea.or.kr/cms/resource/17/2560517_image2_1.jpg",
                    "mapx": 126.9783710306,
                    "mapy": 37.5665986816,
                    "mlevel": 6,
                    "modifiedtime": 20180917153230,
                    "readcount": 12165,
                    "sigungucode": 24,
                    "tel": "053-743-2882~5, 053-961-8969",
                    "title": "경북착한사과 페스티벌 2018"
                },

我进行了很多搜索,但无法解决问题。请帮助我解决问题。

1 个答案:

答案 0 :(得分:1)

您的代码逻辑基本上是正确的。我已将您的代码复制到我的项目中并对其进行了测试。我发现了为什么您的代码不起作用。

请查看以下代码行。

int likeCount = hit.getInt("siguncode");

您的json响应中没有字段siguncode。相反,您有sigungucode字段。这就是为什么您的代码无法正常工作的原因。

  

PS:JSONObject和JSONArray之间的区别

     

JSONObject只是具有键/值映射的对象。

     

JSONArray是具有一个或多个JSONObject的集合。

在您的JSON示例中,"header"是JSONObject。 "item"中的"items"是JSONArray。

编辑

为了解决您的问题,您应该执行以下操作。 只需替换您的代码行:

int likeCount = hit.getInt("siguncode");

与此:

int likeCount = hit.getInt("sigungucode");

编辑第一张图片

for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject hit = jsonArray.getJSONObject(i);

    String creatorName = hit.getString("title");
    String imageUrl = hit.getString("firstimage");
    int likeCount = hit.getInt("sigungucode");
    String firstimage = "";
    if (hit.has("firstimage")) {
        firstimage = hit.getString("firstimage");
    }

    mExampleList.add(new ExampleItem(imageUrl, creatorName, likeCount));
}