How to Convert JSON array string to List

How to Convert JSON array string to List - Hello friend inabnomaniiyaha, In the article that you read this time with the title How to Convert JSON array string to List, we have prepared this article well for you to read and take information in it. hopefully the contents of the post Artikel Code-java-example,what we write you can understand. Alright, happy reading.

Judul : How to Convert JSON array string to List
link : How to Convert JSON array string to List

Baca juga


How to Convert JSON array string to List

 How to Convert JSON array string to List

1. Convert JSON array string to List

1.1 JSON array string

[{"name":"mkyong", "age":37}, {"name":"fong", "age":38}]

1.2 Create an object to map the above JSON fields.

public class Person {

    String name;

    Integer age;

    //getters and setters

}

1.3 Convert the JSON array string to a List

public class JacksonArrayExample {


    public static void main(String[] args) {


        ObjectMapper mapper = new ObjectMapper();

        String json = "[{\"name\":\"mkyong\", \"age\":37}, {\"name\":\"fong\", \"age\":38}]";


        try {


            // 1. convert JSON array to Array objects

            Person[] pp1 = mapper.readValue(json, Person[].class);


            System.out.println("JSON array to Array objects...");

            for (Person person : pp1) {

                System.out.println(person);

            }


            // 2. convert JSON array to List of objects

            List<Person> ppl2 = Arrays.asList(mapper.readValue(json, Person[].class));


            System.out.println("\nJSON array to List of objects");

            ppl2.stream().forEach(x -> System.out.println(x));


            // 3. alternative

            List<Person> pp3 = mapper.readValue(json, new TypeReference<List<Person>>() {});


            System.out.println("\nAlternative...");

            pp3.stream().forEach(x -> System.out.println(x));


        } catch (IOException e) {

            e.printStackTrace();

        }


    }

}

Output

1. JSON array to Array objects...

Person{name='mkyong', age=37}

Person{name='fong', age=38}


2. JSON array to List of objects

Person{name='mkyong', age=37}

Person{name='fong', age=38}


3. Alternative...

Person{name='mkyong', age=37}

Person{name='fong', age=38}



That's the article How to Convert JSON array string to List

That's it for the article How to Convert JSON array string to List this time, hopefully can be useful for all of you. well, see you in another article post.

You are now reading the article How to Convert JSON array string to List with link addresshttps://inabnonapudyawanabing.blogspot.com/2021/05/how-to-convert-json-array-string-to-list.html

0 Response to " How to Convert JSON array string to List"

Post a Comment

Tips Tricks for Android Phone

Tips & Tricks for Android Phone is a free android app and Collection of Tips and Tricks related to using your android mobile device lik...