从 URL 获取 JSON 数组并将其转换为 Android 中的 HashMap

Posted

技术标签:

【中文标题】从 URL 获取 JSON 数组并将其转换为 Android 中的 HashMap【英文标题】:Getting a JSON array from an URL and converting it into a HashMap in Android 【发布时间】:2015-09-08 20:17:12 【问题描述】:

我有一个 URL,例如 www.example.com/movies/,它有以下 JSON 数组:

[
    
        "id": "alice",
        "director": "Tim Burton",
        "year": "2010",
        "image":"alice",
        "length": "108 min",
        "stars": "Mia Wasikowska, Johnny Depp, Helena Bonham Carter",
        "name": "Alice in Wonderland",
        "description": "Nineteen-year-old Alice returns to the magical world from her childhood adventure, where she reunites with her old friends and learns of her true destiny: to end the Red Queen's reign of terror.",
        "rating": "6.5",
        "url": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BMTMwNjAxMTc0Nl5BMl5BanBnXkFtZTcwODc3ODk5Mg@@._V1_SY317_CR0,0,214,317_AL_"
    ,
    
        "id": "avator",
        "director": "Cameron",
        "year": "2009",
        "image":"avatar",
        "length": "162 min",
        "stars": "Sam Worthington, Zoe Saldana, Sigourney Weaver",
        "name": "Avatar",
        "description": "A paraplegic Marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
        "rating": "7.9",
        "url": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SY317_CR0,0,214,317_AL_"
    ]

我想从 android 获取这个 JSON 数组并将其转换为 Hashmap。请帮帮我。

【问题讨论】:

看看How to ask question in SO? ***.com/questions/21720759/…的可能重复 1) ***.com/questions/9605913/… 2) ***.com/questions/22011200/… 请看我的回答。 【参考方案1】:

您可以从 URL 获取 JSON 响应

    HttpClient client;
    String _responseMain = "";
    HttpResponse responseMain;


        AsyncTask<String, String, String> _Task = new AsyncTask<String, String, String>() 

            @Override
            protected void onPreExecute() 


            

            @Override
            protected String doInBackground(String... arg0) 
            

                if (NetworkAvailablity.checkNetworkStatus(CurrentActivity.this)) 
                




                    try 
                        // Creating HTTP client
                        client = new DefaultHttpClient();

                        // Creating HTTP Post
                        HttpGet httpGet= new HttpGet("http://api.myjson.com/bins/44tys%22");




                        responseMain = client.execute(httpGet);
                        HttpEntity entitity = responseMain.getEntity();

                        _responseMain = EntityUtils.toString(entitity); // content will be consume only once
                System.out.println("Response : "+_responseMain);


                     catch (UnsupportedEncodingException e) 
                        // writing error to Log
                        e.printStackTrace();

                    
                    catch (Exception e) 
                        // TODO: handle exception
                        e.printStackTrace();


                    


                 
                else
                

                

                return null;

            
            @Override
            protected void onPostExecute(String result) 
            
                if (_responseMain!=null&&!_responseMain.equalsIgnoreCase("")) 
 try 
                            JSONArray _jArr = new JSONArray("YOUR_JSON_STRING");
                            HashMap<String, String> pairs = new HashMap<String, String>();
                            if (_jArr.length()>0) 

                                for (int i = 0; i < _jArr.length(); i++) 
                                    JSONObject _jObject = _jArr.getJSONObject(i);
                                    String _id = _jObject.getString("id");
                                    pairs.put("id", _id);

                                    String _director = _jObject.getString("director");
                                    pairs.put("director", _director);

                                    String _year = _jObject.getString("year");
                                    pairs.put("year", _year);

                                    String _image = _jObject.getString("image");
                                    pairs.put("image", _image);

                                    String _length = _jObject.getString("length");
                                    pairs.put("length", _length);

                                    String _stars = _jObject.getString("stars");
                                    pairs.put("stars", _stars);

                                    String _name = _jObject.getString("name");
                                    pairs.put("name", _name);

                                    String _description = _jObject.getString("description");
                                    pairs.put("description", _description);

                                    String _rating= _jObject.getString("rating");
                                    pairs.put("rating", _rating);

                                    String _url = _jObject.getString("url");
                                    pairs.put("url", _url);

                                
                            

                            



                         catch (JSONException e) 
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                                           

                 else 

                

            
        ;
        _Task.execute((String[]) null);

【讨论】:

前导下划线只会让可读性变差,恕我直言 非常感谢您的回复,Shoeb。但是我还没有在我的项目中保存 json 文件。我必须从 URL 中获取它。而且我必须在列表中填充值。 您可以在列表中填充值,因此您可以使用我制作的字符串值。 我有将 json 数组转换为 hashmap 的代码。我需要一个代码来从这个 url "api.myjson.com/bins/44tys" 读取 json 代码。这个 URL 有我的 json 代码。

以上是关于从 URL 获取 JSON 数组并将其转换为 Android 中的 HashMap的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PostgreSQL 中获取表的每一天的第一个日期并将其转换为 JSON

如何将 JSON 字符串转换为数组

如何从 url 获取 json 数据并将其保存到 const 变量 [TypeScript]

C# http-get url JSON 数据并将其解析为文本..?

如何从字符串中获取子字符串并将另一个字符串附加到字符串并将其转换为数组

从 URL 获取图像并将其附加到数组