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条)

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭