Java jsonarray to list

Convert JSON array to a list using Jackson in Java

In this short tutorial, you’ll learn how to use the Jackson library to convert a JSON array string into a list of Java Objects and vice versa.

implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.0' 
dependency> groupId>com.fasterxml.jackson.coregroupId> artifactId>jackson-databindartifactId> version>2.10.0version> dependency> 
[  "name": "John Doe", "email": "john.doe@example.com", "roles": [ "Member", "Admin" ], "admin": true >,  "name": "Tom Lee", "email": "tom.lee@example.com", "roles": [ "Member" ], "admin": false > ] 

To convert the above JSON array to a list of Java Objects, let us first create a simple User class to map JSON fields:

public class User  public String name; public String email; private String[] roles; private boolean admin; public User()  > public User(String name, String email, String[] roles, boolean admin)  this.name = name; this.email = email; this.roles = roles; this.admin = admin; > // getters and setters, toString() . (omitted for brevity) > 

Now we can use the readValue() method from the ObjectMapper class to transform the above JSON array to a list of User objects, as shown below:

try  // JSON array String json = "[ + "\"roles\":[\"Member\",\"Admin\"],\"admin\":true>, + "\"email\":\"tom.lee@example.com\",\"roles\":[\"Member\"],\"admin\":false>]"; // convert JSON array to Java List ListUser> users = new ObjectMapper().readValue(json, new TypeReferenceListUser>>() >); // print list of users users.forEach(System.out::println); > catch (Exception ex)  ex.printStackTrace(); > 
Username='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true> Username='Tom Lee', email='tom.lee@example.com', roles=[Member], admin=false> 
User[] users = new ObjectMapper().readValue(json, User[].class); 

If your JSON array is stored in a JSON file, you can still read and parse its content to a list of Java Objects, as shown below:

ListUser> users = new ObjectMapper().readValue(Paths.get("users.json").toFile(), new TypeReferenceListUser>>()  >); 

The following example demonstrates how to use the writeValueAsString() method from the ObjectMapper class to convert a list of Java Objects to their JSON array representation:

try  // create a list of users ListUser> users = Arrays.asList( new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true), new User("Tom Lee", "tom.lee@example.com", new String[]"Member">, false) ); // convert users list to JSON array String json = new ObjectMapper().writeValueAsString(users); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 
["name":"John Doe","email":"john.doe@example.com","roles":["Member","Admin"],"admin":true>, "name":"Tom Lee","email":"tom.lee@example.com","roles":["Member"],"admin":false>] 
try  // create a list of users ListUser> users = Arrays.asList( new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true), new User("Tom Lee", "tom.lee@example.com", new String[]"Member">, false) ); // convert users list to JSON file new ObjectMapper().writeValue(Paths.get("users.json").toFile(), users); > catch (Exception ex)  ex.printStackTrace(); > 

For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Programming Blog

Welcome To Programming Tutorial. Here i share about Java Programming stuff. I share Java stuff with simple examples.

Search This Blog

How to convert JSONObject and JSONArray into Java List | JSONArray and JSONObject

Convert JSON Object data into Java List and Display accordingly | Convert String JSONObject and JSONArray data into List in Java

Convert JSON Object and JSONarray into Java List

Often times we need to call Third party API and we get JSON response, and want to display data into web page. Sometimes we got complex JSON response and difficult to convert into Java data structure.

First learn how to call third party rest API in Java.

So lets see how we can easily convert JSON data into our Java data structure. Following sample JSON data.

"ProgrammingList": [
"id": "1",
"name": "Java",
"edition": "third"
>,
"id": "2",
"name": "Python",
"edition": "fourth"
>,
"id": "3",
"name": "JavaScript",
"edition": "Fifth"
>,
"id": "4",
"name": "c#",
"edition": "second"
>
],

>

For below example you must need org.json library. For that you can do following things.

  1. Create Web Dynamic Project in Eclipse and add «java-json.jar» into WebContent -> WEB-INF -> lib folder.
  2. Create maven project and add following dependency in pom.xml file

Example 1 : Convert and display JSON String Object into Java ArrayList

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ConvertJsonObjectToList
public static void main(String[] args) try convertJsonToList();
> catch (JSONException e) // TODO Auto-generated catch block
e.printStackTrace();
>
>

public static void convertJsonToList() throws JSONException
// JSON data in string
String programmingData = " + " \"ProgrammingList\": [\r\n"
+ " + " \"id\": \"1\",\r\n"
+ " \"name\": \"Java\",\r\n"
+ " \"edition\": \"third\"\r\n"
+ " >,\r\n"
+ " + " \"id\": \"2\",\r\n"
+ " \"name\": \"Python\",\r\n"
+ " \"edition\": \"fourth\"\r\n"
+ " >,\r\n"
+ " + " \"id\": \"3\",\r\n"
+ " \"name\": \"JavaScript\",\r\n"
+ " \"edition\": \"Fifth\"\r\n"
+ " >,\r\n"
+ " + " \"id\": \"4\",\r\n"
+ " \"name\": \"c#\",\r\n"
+ " \"edition\": \"second\"\r\n"
+ " >\r\n"
+ " ],\r\n"
+ " \r\n"
+ ">";

// Get 'ProgrammingList' Object data into string
String objectData = new JSONObject(programmingData).get("ProgrammingList").toString();

// creating JSONArray of string objectData
JSONArray jsonArray = new JSONArray(objectData);;

List> listOfAllData = new ArrayList<>();

// Traverse through jsonArray and put data into map of list
for(int index = 0; index < jsonArray.length(); index++)
Map mapOfEachData = new HashMap<>();
JSONObject eachObject = new JSONObject(jsonArray.get(index).toString());
mapOfEachData.put("id", eachObject.get("id").toString());
mapOfEachData.put("name", eachObject.getString("name").toString());
mapOfEachData.put("edition", eachObject.getString("edition").toString());
listOfAllData.add(mapOfEachData);
>

// Print All Json data
for (Map entry : listOfAllData) System.out.print("Id : " + entry.get("id") + ", Programming Language : "
+entry.get("name") + ", Edition : "
+entry.get("edition") +"\n");
>
>

>

Id : 1, Programming Language : Java, Edition : third
Id : 2, Programming Language : Python, Edition : fourth
Id : 3, Programming Language : JavaScript, Edition : Fifth
Id : 4, Programming Language : c#, Edition : second

  • Getting «ProgrammingList» JSONObject into String objectData.
  • Creating new JSONArray of String objectData.
  • Traverse through jsonArray. (here we have 4 objects in jsonArray).
  • Getting one by one JSONObject and put in Map with String name as key and String data as value.
  • Add map into list of map after creating map of given data.
  • Print all list of map data one by one.

Lets see another example. following the JSON structure.

"StudentList": "students": [
"student_id" : "1",
"student_name" : "student_one"
"subjects_mark": [
"subject": "java",
"mark": "80",
>,
"subject": "python",
"mark": 50,
>
],
>,
"student_id" : "2",
"student_name" : "student_two"
"subjects_mark": [
"subject": "java",
"mark": "50",
>,
"subject": "python",
"mark": 60,
>
],
>,
"student_id" : "3",
"student_name" : "student_three"
"subjects_mark": [
"subject": "java",
"mark": "75",
>,
"subject": "python",
"mark": 80,
>
],
>,
"student_id" : "4",
"student_name" : "student_four"
"subjects_mark": [
"subject": "java",
"mark": "55",
>,
"subject": "python",
"mark": 65,
>
],
>
>

Example 2 : Convert List of JSON Object to Java Map of List

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ConvertJsonDemo
public static void main(String[] args)
try onvertJsonToList();
> catch (JSONException e) // TODO Auto-generated catch block
e.printStackTrace();
>
>

public static void onvertJsonToList() throws JSONException
String studentsData = " + " \"StudentList\": + " \"students\": [\r\n"
+ " + " \"student_id\": \"1\",\r\n"
+ " \"student_name\": \"student_one\",\r\n"
+ " \"subjects_mark\": [\r\n"
+ " + " \"subject\": \"java\",\r\n"
+ " \"mark\": \"80\"\r\n"
+ " >,\r\n"
+ " + " \"subject\": \"python\",\r\n"
+ " \"mark\": \"50\"\r\n"
+ " >\r\n"
+ " ]\r\n"
+ " >,\r\n"
+ " + " \"student_id\": \"2\",\r\n"
+ " \"student_name\": \"student_two\",\r\n"
+ " \"subjects_mark\": [\r\n"
+ " + " \"subject\": \"java\",\r\n"
+ " \"mark\": \"70\"\r\n"
+ " >,\r\n"
+ " + " \"subject\": \"python\",\r\n"
+ " \"mark\": \"60\"\r\n"
+ " >\r\n"
+ " ]\r\n"
+ " >,\r\n"
+ " + " \"student_id\": \"3\",\r\n"
+ " \"student_name\": \"student_three\",\r\n"
+ " \"subjects_mark\": [\r\n"
+ " + " \"subject\": \"java\",\r\n"
+ " \"mark\": \"85\"\r\n"
+ " >,\r\n"
+ " + " \"subject\": \"python\",\r\n"
+ " \"mark\": \"75\"\r\n"
+ " >\r\n"
+ " ]\r\n"
+ " >,\r\n"
+ " + " \"student_id\": \"4\",\r\n"
+ " \"student_name\": \"student_four\",\r\n"
+ " \"subjects_mark\": [\r\n"
+ " + " \"subject\": \"java\",\r\n"
+ " \"mark\": \"65\"\r\n"
+ " >,\r\n"
+ " + " \"subject\": \"python\",\r\n"
+ " \"mark\": \"55\"\r\n"
+ " >\r\n"
+ " ]\r\n"
+ " >\r\n"
+ " ]\r\n"
+ " >\r\n"
+ ">\r\n"
+ "";

String objectData = new JSONObject(studentsData).get("StudentList").toString();
JSONArray studentsJsonArray = new JSONArray(
new JSONObject(objectData).get("students").toString());

List> listOfAllData = new ArrayList<>();

for (int i = 0; i < studentsJsonArray.length(); i++)
Map mapOfEachData = new HashMap<>();
String data = studentsJsonArray.get(i).toString();

JSONObject eachStudentObj = new JSONObject(data);

String studentName = eachStudentObj.get("student_name").toString();

mapOfEachData.put("name", studentName);

JSONArray marksArray = new JSONArray(
new JSONObject(data).get("subjects_mark").toString());

for (int j = 0; j < marksArray.length(); j++) String eachSubjectMark = marksArray.get(j).toString();
JSONObject eachBOObjectMarkObj = new JSONObject(eachSubjectMark);
mapOfEachData.put(eachBOObjectMarkObj.getString("subject"),
eachBOObjectMarkObj.getString("mark"));
>

listOfAllData.add(mapOfEachData);
>

for (Map entry : listOfAllData) System.out.println(entry);
>

>

>

  • Get «StudentList» JSON Object as String format.
  • After store students JSON Object into JSONArray.
  • Traverse through studentsJsonArray.
  • Get each String student object into JSONObject. Get student name and putted in map.
  • After we also have subjects_mark JSONArray in students Object.
  • Loop through subject_mark JSONArray and putted subject name and marks in listOfAllData.
  • Last, print all list of map data one by one.

Источник

Java jsonarray to list

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Import certificate to keystore in java
Оцените статью