繁体   English   中英

Android和Json解析

[英]Android and Json parsing

我试图让我的应用程序连接到rest API并从中获取数据。 到目前为止,我已经获取了数据。 但我不知道如何解析它。 我相信那就是你下一步要做的。

这是我的代码的一部分,该代码与我的其余API相连并获取数据。 我得到的错误是JSONArray无法转换为JSONObject

 if (status == 200) {
                InputStream is = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String responseString;
                StringBuilder sb = new StringBuilder();

                while ((responseString = reader.readLine()) != null) {
                    sb = sb.append(responseString);
                }
                String speciesListData = sb.toString();
                species= SpeciesJson.fromJson(speciesListData);
                Log.d(Constants.TAG, "speciesJSON: " + species);
                return true;
            }

这是我尝试解析的结果,直到现在为止一切正常。 她的电话是我尝试解析的电话

species= SpeciesJson.fromJson(speciesListData);

而这就是它打破了大声笑

public class SpeciesJson {
    private String scientific_name, name,description;


    public SpeciesJson (JSONObject species) throws JSONException {

        this.scientific_name=species.optString("scientific_name");
        this.name=species.optString("name");
        this.description=species.optString("description");

    }
    public static ArrayList<SpeciesJson> fromJson(String photoData) throws JSONException {
        ArrayList<SpeciesJson> speciesData = new ArrayList<>();
        JSONObject data = new JSONObject(photoData);
        JSONObject photos = data.optJSONObject("name");
        JSONArray photoArray = photos.optJSONArray("name");

        for (int i = 0; i < photoArray.length(); i++) {
            JSONObject photo = (JSONObject) photoArray.get(i);
            SpeciesJson currentPhoto = new SpeciesJson(photo);
            speciesData.add(currentPhoto);
        }
        return speciesData;
    }

因此,当我使用我制作的解析方法运行它时,它不起作用。

下面是hte json数据的示例,我试图在视图中显示科学名称和名称

  {
        "id": 1,
        "scientific_name": "Platanus racemosa",
        "name": "California Sycamore",
        "description": "typically in river areas, but planted all throughout L.A",
        "type": 1
    },
    {
        "id": 2,
        "scientific_name": "Pyrus kawakamii",
        "name": "Ornamental Pear",
        "description": "native to Asia, commonly planted in L.A",
        "type": 1
    },
    {
        "id": 3,
        "scientific_name": "Liquidambar styraciflua",
        "name": "American Sweetgum",
        "description": "native to SE U.S, planted all around L.A",
        "type": 1
    },
    {
        "id": 4,
        "scientific_name": "Setophaga coronata",
        "name": "Yellow-rumped Warbler",
        "description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
        "type": 2
    },
    {
        "id": 5,
        "scientific_name": "Calypte anna",
        "name": "Anna's Hummingbird",
        "description": "native bird, does not migrate. Spends the year in L.A",
        "type": 2
    },
    {
        "id": 6,
        "scientific_name": "Regulus calendula",
        "name": "Ruby-crowned Kinglet",
        "description": "native bird, spends the winter in L.A before migrating north during the summer to breed",
        "type": 2
    }
]

我亲爱的朋友使用google的GSON库即可。

在您的帮助下,我使此操作变得简单。

使此类成为SpeciesJson.java

public class SpeciesJson {

   private String scientific_name;
   private String name;
   private String description;

public SpeciesJson() {
}

public SpeciesJson(String scientific_name,String name,String description) {
     this.scientific_name = scientific_name;
     this.name = name;
     this.description = description;
}


//And getter,setters
}

如果SpeciesJson是简单的对象,则使用此对象

Gson gson = new Gson();
SpeciesJson species = gson.fromJson(responseString,SpeciesJson.class);

如果SpeciesJson是ArrayList,则使用它(看起来像您的情况,因此请在您的Json响应包含多个SpeciesJson对象时进行检查)

Gson gson = new Gson();
ArrayList<SpeciesJson> species = new ArrayList<>();
SpeciesJson[] speciesarray = (SpeciesJson[]) gson.fromJson(responseString,SpeciesJson[].class);
Collections.addAll(species, speciesarray);

如果您想了解有关Gson库的更多信息,请检查此链接https://guides.codepath.com/android/Leveraging-the-Gson-Library

好了,您可以使用GSON来解析数据,并使用Volley来获取数据。

//Create volley request
            String url = String.format("SOME_URL", arrayOfObject);

        RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // we got the response, now our job is to handle it
                try {                        
                    ArrayList<SpeciesJson> speciesData = getDataFromJson(stream);

                } catch (RemoteException | OperationApplicationException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //something happened, treat the error.
                Log.e("Error", error.toString());
            }
        });

        queue.add(request);

//If your JSON data is an Array
    private static List<SpeciesJson> getDataFromJson(String json) {
        Gson gson = new GsonBuilder().create();
        List<SpeciesJson> result = new ArrayList<>();
        try {
            JSONObject posts=new JSONObject(json);
            JSONArray dataArray=posts.getJSONArray("data");
            for(int n = 0; n < dataArray.length(); n++)
            {
                JSONObject object = dataArray.getJSONObject(n);
                result.add(gson.fromJson(object.toString(), SpeciesJson.class));
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

和排球服务

public class VolleyService {

    private static VolleyService instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private VolleyService(Context context) {
        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url,bitmap);
            }
        });
    }

    public static VolleyService getInstance(Context context) {
        if (instance == null) {
            instance = new VolleyService(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

或者,您可以使用Retrofit库为您解析它:

http://www.vogella.com/tutorials/Retrofit/article.html https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit

您应该在GsonConverterFactory中使用改造库 管理网络响应的最佳解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM