首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android和Json解析

Android和Json解析
EN

Stack Overflow用户
提问于 2016-01-18 15:52:51
回答 3查看 107关注 0票数 0

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

下面是我的代码片段,它连接到我的rest API并获取数据。我得到的错误是无法将JSONArray转换为JSONObject

代码语言:javascript
复制
 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;
            }

这就是我尝试解析它的时候,它在这里之前工作得很好。她的就是我试图解析的那一行

代码语言:javascript
复制
species= SpeciesJson.fromJson(speciesListData);

这就是它坏掉的原因

代码语言:javascript
复制
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;
    }

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

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

代码语言:javascript
复制
  {
        "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
    }
]
EN

回答 3

Stack Overflow用户

发布于 2016-01-18 16:12:46

我亲爱的朋友使用谷歌GSON库,就是这样。

因为你的帮助,我让这件事变得更容易了。

将此类设为SpeciesJson.java

代码语言:javascript
复制
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是一个简单的对象,那么使用这个

代码语言:javascript
复制
Gson gson = new Gson();
SpeciesJson species = gson.fromJson(responseString,SpeciesJson.class);

如果SpeciesJson是一个ArrayList,那么使用它(它看起来像你的情况,所以检查一下,因为你的Json响应包含多个SpeciesJson对象)

代码语言:javascript
复制
Gson gson = new Gson();
ArrayList<SpeciesJson> species = new ArrayList<>();
SpeciesJson[] speciesarray = (SpeciesJson[]) gson.fromJson(responseString,SpeciesJson[].class);
Collections.addAll(species, speciesarray);

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

票数 1
EN

Stack Overflow用户

发布于 2016-01-18 16:17:02

您可以使用GSON来解析数据,然后使用Volley来获取数据。

代码语言:javascript
复制
//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;
    }

和截击服务

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2016-01-18 16:18:33

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34849630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档