有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将Java对象转换为JSON

这是一个春季项目。我有一个物品清单:

List<User> userList = new ArrayList<>();
userList.add(new User("user1", "password1"));
userList.add(new User("user2", "password2"));
userList.add(new User("user3", "password3"));
userList.add(new User("user4", "password4"));

如何将列表转换为JSON数组


共 (3) 个答案

  1. # 1 楼答案

    试试这个:

    import java.util.*;
    import org.json.simple.*;
    
    // this method converts a list to JSON Array
    String jsonStr = JSONArray.toJSONString(userList);
    
  2. # 2 楼答案

    List<User> userList = new ArrayList<>();
    userList.add(new User("user1", "password1"));
    userList.add(new User("user2", "password2"));
    userList.add(new User("user3", "password3"));
    userList.add(new User("user4", "password4"));
    
    JSONArray jsonArray = new JSONArray(userList );
    System.out.println(jsonArray);
    
    For this you need to import:
    import org.json.JSONArray;
    
  3. # 3 楼答案

    尝试以下解决方案:

    String json = new Gson().toJson(userList);
    

    以下是Gson的maven依赖项:

    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.6</version>
    </dependency>
    

    或者从这里下载lib文件: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.6/jar