0

It is a Spring project. I have a list of objects:

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"));

How to convert the list to JSON array?

4

5 Answers 5

2

Add the below dependency to your project:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.7</version>
        </dependency>

Then try below code :

    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"));
    ObjectMapper mapper = new ObjectMapper();
    String string = mapper.writeValueAsString(userList);
1

Try this:

import java.util.*;
import org.json.simple.*;

// this method converts a list to JSON Array
String jsonStr = JSONArray.toJSONString(userList);
1

Try this solution:

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

Here is the maven dependency for Gson:

<!-- 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>

or download the lib file from here: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.6/jar

1

You can convert them to array or object using json. below is a sample code


// import packages
import org.json.JSONArray;
import org.json.JSONObject;


// sample code

JSONObject jsonObj = new JSONObject(byteArray);
JSONObject response = (JSONObject) jsonObj.getJSONArray("passwords").get(0);
JSONArray localizedObjectAnnotations = (JSONArray) response.getJSONArray("password1");  // if an array


// you can now iterate to get more data
for (int k = 0; k < localizedObjectAnnotations.length(); k++) {
    JSONObject buttonDetails = (JSONObject) localizedObjectAnnotations.get(k);
    this.tmpItem = new Item();
    this.tmpItem.setName(buttonDetails.get("name").toString());
}

1
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;

Not the answer you're looking for? Browse other questions tagged or ask your own question.