java如何解析json字符串_我的世界json文件怎么用

java如何解析json字符串_我的世界json文件怎么用在 Java 中解析 JSON 字符串数组通常有以下几种方法 1 使用官方的 org json 库 javaimport org json JSONArray import org json JSONObject public class JsonArrayExa public static void main String args String

在Java中解析JSON字符串数组通常有以下几种方法:

1. 使用官方的`org.json`库:

 import org.json.JSONArray; import org.json.JSONObject; public class JsonArrayExample { public static void main(String[] args) { String jsonArrayStr = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":28, \"city\":\"Los Angeles\"}]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println("Name: " + jsonObject.getString("name")); System.out.println("Age: " + jsonObject.getInt("age")); System.out.println("City: " + jsonObject.getString("city")); } } } 

2. 使用Gson库:

 import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; public class GsonExample { public static void main(String[] args) { String jsonArrayStr = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":28, \"city\":\"Los Angeles\"}]"; Gson gson = new Gson(); Type listType = new TypeToken 
  
    
  
    >(){}.getType(); 
   List 
  
    
  
    persons = gson.fromJson(jsonArrayStr, listType); 
   for (Person person : persons) { System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); System.out.println("City: " + person.getCity()); } } } 

3. 使用Fastjson库:

 import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import java.util.List; public class FastjsonExample { public static void main(String[] args) { String jsonArrayStr = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, {\"name\":\"Jane\", \"age\":28, \"city\":\"Los Angeles\"}]"; JSONArray jsonArray = JSON.parseArray(jsonArrayStr); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); System.out.println("Name: " + jsonObject.getString("name")); System.out.println("Age: " + jsonObject.getInteger("age")); System.out.println("City: " + jsonObject.getString("city")); } } } 

以上示例展示了如何使用不同的库解析JSON字符串数组。请根据您的项目需求选择合适的库。

编程小号
上一篇 2025-05-21 15:35
下一篇 2025-01-09 11:35

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/57295.html