简体   繁体   中英

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:

{"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:

["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...

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. Under the covers, Spring MVC uses Jackson. You would be best off searching Google for Jackson tutorials and looking at official docs at 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.

Firstly for a list of User object the JSON needs to be different. 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

 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. There are various other parsers available like jackson,ig-parser(by instagram). here is an example using 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

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

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

Just include in maven:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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