dongyimo1293 2016-08-14 20:14
浏览 92
已采纳

在android不同格式的JSON解析

I have php file that has json format output that looks exactly like below:

{"id":"45","name":"testtest","phone":"123456","address":"test123"}

What I want to do is to parse it in my android application and get all the fields of json. The thing is that this format is JSON Object and not JSON Array which makes it hard for me to understand how am I going to parse it. Can you help me figure out how? Here is where I call the my url and I also have a JSONParser class. The problem is that I get Null Pointer Exception when I am trying to get my object json.getJSONObject(0);

 protected String doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();
        // get JSON data from URL
        JSONArray json = jParser.getJSONFromUrl(url);
            try {

                JSONObject c = json.getJSONObject(0);
                String id= c.getString(ID);
                String name = c.getString(NAME);
                String phone= c.getString(PHONE);
                String address= c.getString(ADDRESS);


            } catch (JSONException e) {
                e.printStackTrace(); }
         response = name;

        return response;
    }
  • 写回答

2条回答 默认 最新

  • douzhanjia0773 2016-08-15 05:16
    关注

    Its simple ... create JSONObejct from String as you create JSONArray like ;;

    JSONObject jsonObject = new JSONObject(provided_json);
    

    Then get a item from jsonObject as

    String id= jsonObject .getString(ID);
    

    Full example here ...

    //String provided_json = {"id":"45","name":"testtest","phone":"123456","address":"test123"}
    
        JSONObject jsonObject = new JSONObject(provided_json);
        String id= jsonObject .getString(ID);
        String name = jsonObject .getString(NAME);
        String phone= jsonObject .getString(PHONE);
        String address= jsonObject .getString(ADDRESS);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗