Java gson fromjson array

How to read and write JSON using Gson in Java

In my previous article, we looked at reading and writing JSON files in Java using different open-source libraries like JSON.simple, Jackson, Moshi, and Gson.

In this article, you’ll learn how to read and write JSON using Gson in detail. Gson is a popular Java library developed and maintained by Google to convert Java Objects into their JSON representation.

It can also convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects, including pre-existing objects you do not modify.

implementation 'com.google.code.gson:gson:2.8.6' 
dependency> groupId>com.google.code.gsongroupId> artifactId>gsonartifactId> version>2.8.6version> dependency> 
public class Book  private String title; private String isbn; private long year; private String[] authors; public Book()  > public Book(String title, String isbn, long year, String[] authors)  this.title = title; this.isbn = isbn; this.year = year; this.authors = authors; > // getters and setters, equals(), toString() . (omitted for brevity) > 

To convert a Java Object to a JSON string, all you need to do is create a new instance of Gson and then call the toJson() method with Java Object as a parameter:

try  // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // convert book object to JSON String json = new Gson().toJson(book); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 
"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]> 

The toJson() method also accepts an instance of Writer as a second parameter that you can use to output the JSON directly to a file, as shown below:

try  // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create Gson instance Gson gson = new Gson(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("book.json")); // convert book object to JSON file gson.toJson(book, writer); // close writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 
"title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]> 

You can also convert a list of Java Objects to a JSON array using the same toJson() method, as shown below:

try  // create books list ListBook> books = Arrays.asList( new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">), new Book("Head First Java", "0596009208", 2003, new String[]"Kathy Sierra", "Bert Bates">) ); // create Gson instance Gson gson = new Gson(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("books.json")); // convert books object to JSON file gson.toJson(books, writer); // close writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 
["title":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]>, "title":"Head First Java","isbn":"0596009208","year":2003,"authors":["Kathy Sierra","Bert Bates"]>] 
try  // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // create a Gson instance with pretty-printing Gson gson = new GsonBuilder().setPrettyPrinting().create(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("book.json")); // convert book object to JSON file gson.toJson(book, writer); // close writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 
 "title": "Thinking in Java", "isbn": "978-0131872486", "year": 1998, "authors": [ "Bruce Eckel" ] > 
try  // create a book map MapString, Object> map = new HashMap>(); map.put("title", "Thinking in Java"); map.put("isbn", "978-0131872486"); map.put("year", 1998); map.put("authors", new String[]"Bruce Eckel">); // create Gson instance Gson gson = new Gson(); // create a writer Writer writer = Files.newBufferedWriter(Paths.get("book.json")); // convert book object to JSON file gson.toJson(map, writer); // close writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 

To convert a JSON string back to an equivalent Java Object, you can use the fromJson() method from Gson :

try  // JSON string String json = " + ",\"year\":1998,\"authors\":[\"Bruce Eckel\"]>"; // create Gson instance Gson gson = new Gson(); // convert a JSON string to a Book object Book book = gson.fromJson(json, Book.class); // print book System.out.println(book); > catch (Exception ex)  ex.printStackTrace(); > 
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]> 

The fromJson() method also accepts an instance of Reader to read and parse the JSON data from a file:

try  // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("book.json")); // convert a JSON string to a Book object Book book = gson.fromJson(reader, Book.class); // print book System.out.println(book); // close reader reader.close(); > catch (Exception ex)  ex.printStackTrace(); > 

The following example shows how to convert a JSON array to a list of Java Objects using the Gson library:

try  // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("books.json")); // convert JSON array to list of books ListBook> books = Arrays.asList(gson.fromJson(reader, Book[].class)); // print books books.forEach(System.out::println); // close reader reader.close(); > catch (Exception ex)  ex.printStackTrace(); > 
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]> Booktitle='Head First Java', isbn='0596009208', year=2003, authors=[Kathy Sierra, Bert Bates]> 

By using Gson, you can also convert a JSON file to a Java Map with the same properties and keys, as shown below:

try  // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("book.json")); // convert JSON file to map Map?, ?> map = gson.fromJson(reader, Map.class); // print map entries for (Map.Entry?, ?> entry : map.entrySet())  System.out.println(entry.getKey() + "=" + entry.getValue()); > // close reader reader.close(); > catch (Exception ex)  ex.printStackTrace(); > 
year=1998.0 isbn=978-0131872486 title=Thinking in Java authors=[Bruce Eckel] 

By default, Gson uses the class field names as JSON property names. With @SerializedName , you can specify a custom JSON property name:

public class Book  @SerializedName("book_name") private String title; private String isbn; private long year; private String[] authors; // . > 
"book_name":"Thinking in Java","isbn":"978-0131872486","year":1998,"authors":["Bruce Eckel"]> 

By default, Gson ignores null fields while serializing a Java Object to its JSON representation:

try  // create book object Book book = new Book("Thinking in Java", null, 1998, null); // create Gson instance Gson gson = new Gson(); // convert book object to JSON String json = gson.toJson(book); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 
"title":"Thinking in Java","year":1998> 

To explicitly include the null fields in the final JSON output, you can use the serializeNulls() method from GsonBuilder :

Gson gson = new GsonBuilder().serializeNulls().create(); 
"title":"Thinking in Java","isbn":null,"year":1998,"authors":null> 

Gson provides multiple ways to exclude fields while serializing or deserializing JSON. By default, all static and transient fields are excluded. However, you can change this default behavior with the excludeFieldsWithModifiers() method. For example, the following configuration excludes static fields only:

Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create(); 

If you want to exclude both static and transient , use the following (which is equivalent to the default configuration):

Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT) .create(); 

If you want to exclude fields explicitly, use the @Expose annotation. It defines the attributes to be excluded from serialization and deserialization to JSON. To enable @Expose , you need to create the Gson object like the below:

Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); 
public class Book  @Expose(serialize = true, deserialize = true) private String title; @Expose private String isbn; @Expose(serialize = false, deserialize = true) private long year; private String[] authors; // . > 
"title":"Thinking in Java","isbn":"978-0131872486"> 

You might also like.

Источник

Gson шпаргалка для Map, List и Array

Постоянно сталкиваясь с парсингом Json всегда подглядываю в старых проектах или на встретившуюся реализацию объекта на stackoverflow.com.

Решил собрать три основных типа в шпаргалку Map, List, Array.

Type itemsMapType = new TypeToken>() <>.getType(); Type itemsListType = new TypeToken>() <>.getType(); Type itemsArrType = new TypeToken() <>.getType(); 

Рассматривается Serialization/Deserialization операции класса:

Serialization/Deserialization выполнен с использованием библиотеки Gson. В качестве «испытуемого» рассматривается класс GoodsItem.

Map mapItems = new HashMap(); mapItems.put(1, new GoodsItem("Samsung", 51200.6f)); mapItems.put(2, new GoodsItem("Lg", 5400.6f)); mapItems.put(3, new GoodsItem("Alcatel", 4500.6f)); String jsonStr = new Gson().toJson(mapItems); System.out.println(jsonStr); 
Map mapItemsDes = new Gson().fromJson(jsonStr, itemsMapType); System.out.println(mapItemsDes.toString()); 
List listItems = new ArrayList(); listItems.add( new GoodsItem("Samsung" , 51200.6f)); listItems.add( new GoodsItem("Lg" , 5400.6f)); listItems.add( new GoodsItem("Alcatel" , 4500.6f)); String jsonStr = new Gson().toJson(listItems); System.out.println(jsonStr); 
List listItemsDes = new Gson().fromJson(jsonStr,itemsListType); System.out.println(listItemsDes.toString()); 
[Samsung : 51200.6, Lg : 5400.6, Alcatel : 4500.6] 
GoodsItem[] arrItems = new GoodsItem[3]; arrItems[0] = new GoodsItem("Samsung", 51200.6f); arrItems[1] = new GoodsItem("Lg", 5400.6f); arrItems[2] = new GoodsItem("Alcatel", 4500.6f); String jsonStr = new Gson().toJson(arrItems); System.out.println(jsonStr); 
GoodsItem[] arrItemsDes = new Gson().fromJson(jsonStr, itemsArrType); System.out.println(Arrays.toString(arrItemsDes)); 
[Samsung : 51200.6, Lg : 5400.6, Alcatel : 4500.6] 

Как видно ArrayList и простой массив объектов преобразуются в одинаковую строку Json.

Полезные инструменты:
parcelabler.com дает возможность по типу класса сгенерировать parcelable методы для Android. Например для класса GoodsItem:

public class GoodsItem implements Parcelable < String name; float price; public GoodsItem(String name, float price) < this.name = name; this.price = price; public String toString()< return name + " : " + price; >protected GoodsItem(Parcel in) < name = in.readString(); price = in.readFloat(); >@Override public int describeContents() < return 0; >@Override public void writeToParcel(Parcel dest, int flags) < dest.writeString(name); dest.writeFloat(price); >@SuppressWarnings("unused") public static final Parcelable.Creator CREATOR = new Parcelable.Creator() < @Override public GoodsItem createFromParcel(Parcel in) < return new GoodsItem(in); >@Override public GoodsItem[] newArray(int size) < return new GoodsItem[size]; >>; > 

jsonschema2pojo.org — Generate Plain Old Java Objects from JSON or JSON-Schema.

Было бы интересно узнать, чем пользуетесь вы в своих проектах.

Источник

Читайте также:  Комплексное обучение javascript 2020 loftschool
Оцените статью