【问题标题】:how to parse json from url in android [closed]如何从android中的url解析json [关闭]
【发布时间】:2019-08-06 04:33:47
【问题描述】:

我遇到了这个问题,如何从 android studio 中的 url 解析 json 下面是我的 json 结构尝试了所有其他方法对我不起作用

网址:http://api.ipstack.com/109.94.137.130?access_key=e9e5de2c993dc6652ed45c3f9dc53daf

{
   "ip":"109.94.137.130",
   "type":"ipv4",
   "continent_code":"EU",
   "continent_name":"Europe",
   "country_code":"GB",
   "country_name":"United Kingdom",
   "region_code":"ENG",
   "region_name":"England",
   "city":"Bedford",
   "zip":"MK42",
   "latitude":52.1073,
   "longitude":-0.4649,
   "location":{
      "geoname_id":2656046,
      "capital":"London",
      "languages":[
         {
            "code":"en",
            "name":"English",
            "native":"English"
         }
      ],
      "country_flag":"http:\/\/assets.ipstack.com\/flags\/gb.svg",
      "country_flag_emoji":"\ud83c\uddec\ud83c\udde7",
      "country_flag_emoji_unicode":"U+1F1EC U+1F1E7",
      "calling_code":"44",
      "is_eu":true
   }
}

请就这个问题提供帮助。提前致谢。

【问题讨论】:

  • 说清楚,你想要什么?
  • How to parse JSON in Java的可能重复
  • 到目前为止你尝试了什么。展示你的努力
  • tried all other methods如果你真的尝试了所有方法,那我们帮不了你。
  • 与全世界共享您的私人访问密钥也是一个坏主意。

标签: java android json


【解决方案1】:

使用改造或 volley 从 API 获取数据。 Sample Retrofit Implementation

使用GSON 库来解析gson。因为,它很容易实现。

解析代码sn-p为:

ModelClass sInfo_parse = new Gson().fromJson(getURLJson, ModelClass.class);

【讨论】:

    【解决方案2】:

    here 的 gradle 文件中添加 volley。现在在您的 java 文件中添加以下行。

    RequestQueue queue = Volley.newRequestQueue(ChangePasswordActivity.this);
    

    现在像下面的方法一样在 onCreate 方法中调用 make StringRequest 构造函数。

            String Url = your url
    
                        Log.d(TAG, Url);
    
                        StringRequest stringRequest = new StringRequest(Request.Method.GET, Url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        Log.d("response", response);
    
    // here you can find your all json value.
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        error.printStackTrace();
                                    }
                                }
                        );
    
                        queue.add(stringRequest);
                    }
    

    【讨论】:

    • 虽然这段代码 sn-p 可能会回答这个问题,但请添加一些解释为什么会这样。这将提供更好的答案并帮助未来的用户了解问题是如何解决的。
    • 你能帮我从 json 结构中检索至少一个值吗
    • 根据你的json文件你想取哪个值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2013-05-31
    相关资源
    最近更新 更多