简体   繁体   English

在Java中将ArrayList转换为JSON对象

[英]Convert ArrayList to JSON Object In Java

Rookie Java question here: I have an ArrayList of values that store properties of my user object, like so: 菜鸟Java问题在这里:我有一个ArrayList值,用于存储用户对象的属性,如下所示:

{"users":["Bob", 35, "230 Elm Street", "bob@website.com"]}

My User Object: 我的用户对象:

public class User{
    private String name;
    private int age;
    private String address;
    private String email;
    //getters & setters
}

I need to map each of these values to their respective properties so that I can return a proper Key/Value JSON Object, like so: 我需要将每个值映射到它们各自的属性,以便可以返回适当的Key / Value JSON对象,如下所示:

["name": "Bob", "age": 35, "address": "230 Elm Street", "email": "bob@website.com"]

I'm a little confused on how to approach this; 我对如何解决这个问题有些困惑; Do I need to use a Map to manually set each keywhile iterating through my list, something like... 在遍历列表时是否需要使用Map手动设置每个键,例如...

for(User user : list){
    HashMap myMap = new HashMap();
    myMap.put("name", user.getName());
    myMap.setAge("age", user.getAge());
    //etc...

}
//Convert Map to JSON
return new JSONObject(myMap);

Or is it simpler than that? 还是比这更简单? Thanks for the help! 谢谢您的帮助!

Your best bet is to learn Jackson serialization APIs. 最好的选择是学习Jackson序列化API。 Under the covers, Spring MVC uses Jackson. 在幕后,Spring MVC使用Jackson。 You would be best off searching Google for Jackson tutorials and looking at official docs at https://github.com/FasterXML/jackson 您最好在Google上搜索Jackson教程,然后在https://github.com/FasterXML/jackson上查看官方文档。

Be aware if you want to tweak your JSON format, then there are Jackson annotations you can add to your Java objects to do so. 请注意,如果您想调整JSON格式,那么可以将Jackson批注添加到Java对象中。

Firstly for a list of User object the JSON needs to be different. 首先,对于User对象列表,JSON需要不同。 The current representation of same would be as below 当前的表示形式如下

{"users":[{"name": "Bob", "age": 35, "address": "230 Elm Street", "email": "bob@website.com"},{"name": "Bob1", "age": 40, "address": "2301 Elm Street", "email": "bob1@website.com"}]}

To map this json with the List<User> we can use ObjectMapper implementation provided in Jackson library 要将这个json与List<User>映射,我们可以使用Jackson库中提供的ObjectMapper实现。

 ObjectMapper mapper = new ObjectMapper();
 List<User> list2 = mapper.readValue(jsonString, TypeFactory.collectionType(List.class, User.class));

Read this Link for more help 阅读此链接以获取更多帮助

you can use Gson provided by google it will do it for you automatically. 您可以使用Gson provided by google它将自动为您完成。 There are various other parsers available like jackson,ig-parser(by instagram). 还有其他各种解析器,例如jackson,ig-parser(通过instagram)。 here is an example using gson. 这是使用gson的示例。

public class DataObject {

    private int data1 = 100;
    private String data2 = "hello";
    private List<String> list = new ArrayList<String>() {
      {
        add("String 1");
        add("String 2");
        add("String 3");
      }
    };

    //getter and setter methods

    @Override
    public String toString() {
       return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
        + list + "]";
    }

}

Converting to json 转换为json

public class GsonExample {
    public static void main(String[] args) {

    DataObject obj = new DataObject();
    Gson gson = new Gson();

    // convert java object to JSON format,
    // and returned as JSON formatted string
    String json = gson.toJson(obj); 
    System.out.println(json);

    }
}

If you use Spring-MVC, you do not need to know about JSON, it's transparent with @RestController 如果您使用Spring-MVC,则无需了解JSON,@ RestController对JSON是透明的

@RestController
@RequestMapping("user")
public class UserController {
    @RequestMapping
    public User getUser() {
     User user = new User();
     user.setName(...);
     return user;
    }
}

Just include in maven: 只包含在Maven中:

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
</dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM