Android(Java)的JSON
创始人
2024-10-13 07:30:45
0

在Android中,可以使用JSONObject和JSONArray类来解析和生成JSON数据。

以下是一个使用JSONObject解析JSON数据的示例:

String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

try {
    JSONObject jsonObject = new JSONObject(jsonString);
    String name = jsonObject.getString("name");
    int age = jsonObject.getInt("age");
    String city = jsonObject.getString("city");
    
    // 打印解析结果
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("City: " + city);
} catch (JSONException e) {
    e.printStackTrace();
}

以下是一个使用JSONArray解析JSON数组的示例:

String jsonArrayString = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":25, \"city\":\"Los Angeles\"}]";

try {
    JSONArray jsonArray = new JSONArray(jsonArrayString);
    
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        String name = jsonObject.getString("name");
        int age = jsonObject.getInt("age");
        String city = jsonObject.getString("city");
        
        // 打印解析结果
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

如果要生成JSON数据,可以使用JSONObject和JSONArray类的put方法。

以下是一个使用JSONObject生成JSON数据的示例:

JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("name", "John");
    jsonObject.put("age", 30);
    jsonObject.put("city", "New York");
    
    // 将JSON对象转换为字符串
    String jsonString = jsonObject.toString();
    
    // 打印生成的JSON字符串
    System.out.println(jsonString);
} catch (JSONException e) {
    e.printStackTrace();
}

以上是一些使用Android中的JSON包解析和生成JSON数据的示例。可以根据具体需求进行相应的修改和扩展。

相关内容

热门资讯

2024教程!wepoker怎... 1、2024教程!wepoker怎么增加运气,pokemmo脚本辅助下载,高科技教程(有挂辅助)。2...
盘点一款!We poker辅助... 盘点一款!We poker辅助器下载,hhpoker到底可以作弊吗,透明挂教程(有挂神器)是由北京得...
玩家必看攻略!we-poker... 《玩家必看攻略!we-poker是什么软件,aapoker怎么开辅助器,插件教程(有挂技巧)》 aa...
玩家必看科普!约局吧开挂神器是... 玩家必看科普!约局吧开挂神器是真的吗,wepoker好友助力码,力荐教程(有挂技巧);《WPK辅助透...
交流学习经验!werplan辅... 自定义wepoker辅助真的假的系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
教程辅助!wepoker有没有... 教程辅助!wepoker有没有挂,hhpoker是正品吗,技巧教程(有挂软件);《WPK辅助透视》‌...
最新通报!wepoker怎么设... 1、最新通报!wepoker怎么设置房间,wepoker辅助真的假的,AA德州教程(有挂教程)(UU...
热点讨论!hhpoker辅助器... 热点讨论!hhpoker辅助器,hh poker透视器下载,高科技教程(有挂透明);人气非常高,ai...
重大消息!wepoker透视苹... 重大消息!wepoker透视苹果系统,wepoker怎么设置盖牌,必胜教程(有挂技巧);人气非常高,...
交流学习经验!wepoker免... 交流学习经验!wepoker免费辅助器,hhpoker免费辅助器,辅助教程(有挂攻略);人气非常高,...