[JAVA] I tried using Gson

What is Gson

Just quote.

Gson Gson is a Java library that can be used to convert Java Objects into their JSON >representation. It can also be used to convert a JSON string to an equivalent Java object. >Gson can work with arbitrary Java objects including pre-existing objects that you do not have >source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of >them require that you place Java annotations in your classes; something that you can not do if >you do not have access to the source-code. Most also do not fully support the use of Java >Generics. Gson considers both of these as very important design goals.

Samples used in the experiment

Person1.java


import java.util.Date;
public class Person1 {

    private Integer age;
    private String name;
    private String noUse;
    private Date target;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String noUse() {
        return noUse;
    }

    public void noUse(String noUse) {
        this.noUse = noUse;
    }

    public Date target() {
        return target;
    }

    public void target(Date target) {
        this.target = target;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Person1 [age=");
        builder.append(age);
        builder.append(", name=");
        builder.append(name);
        builder.append(", noUse=");
        builder.append(noUse);
        builder.append(", target=");
        builder.append(target);        
        builder.append("]");
        return builder.toString();
    }

}

First, convert to your own type

Ex1.java


public class Sample {
    public static void main(String[] args){
        //-----------------------------
        //jsonReader experiment
        //-----------------------------
        StringBuilder jsonReader = new StringBuilder();
        jsonReader.append("[");
        jsonReader.append(" {\"age\":1,\"name\":\"Gson Taro\",\"target\":\"2020-02-10\"},");
        jsonReader.append(" {\"age\":2,\"name\":\"Gson Taro\",\"target\":\"2020-02-30\"},");
        jsonReader.append(" {\"age\":3,\"name\":\"Gson Taro\",\"target\":\"2020-02-12\"}");
        jsonReader.append("]");

        try {
            Gson gsonReader = new Gson();
            Type listType = new TypeToken<List<Person1>>(){}.getType();
            List<Person1> p1 = gsonReader.fromJson(jsonReader.toString(), listType);

            System.out.println("------------------------------------------->");
            System.out.println("Person1#toString: " + p1);
            System.out.println("------------------------------------------->");
        } catch (Exception e) {
            System.out.println(e.getCause());
            System.out.println("------------------------------------------->");
            if(e.getCause() instanceof NumberFormatException) {
				System.out.println("Numerical error:" + e.getCause().getMessage());
			}else if (e.getCause() instanceof ParseException){ 
				System.out.println("Date input error:" + e.getCause().getMessage());
			}
            System.out.println("------------------------------------------->");
        }
    }

【success】

It's a success without difficulty. The part that passes the type you want to convert to Gson is the liver.

------------------------------------------->
Person1#toString: [Person1 [age=1, name=Gson Taro, noUse=null, target=Mon Feb 10 00:00:00 JST 2020], Person1 [age=2, name=Gson Taro, noUse=null, target=Sun Mar 01 00:00:00 JST 2020], Person1 [age=3, name=Gson Taro, noUse=null, target=Wed Feb 12 00:00:00 JST 2020]]
------------------------------------------->

Next, an experiment to assign null to Integer type

Make the item of Integer type null

test.java


        StringBuilder jsonReader = new StringBuilder();
        jsonReader.append("[");
        jsonReader.append(" {\"age\":null,\"name\":\"Gson Taro\",\"target\":\"2020-02-10\"},");
        jsonReader.append(" {\"age\":2,\"name\":\"Gson Taro\",\"target\":\"2020-02-30\"},");
        jsonReader.append(" {\"age\":3,\"name\":\"Gson Taro\",\"target\":\"2020-02-12\"}");
        jsonReader.append("]");

【success】

By the way, if the recipient is an int type, it will be "0".

------------------------------------------->
Person1#toString: [Person1 [age=null, name=Gson Taro, noUse=null, target=Mon Feb 10 00:00:00 JST 2020], Person1 [age=2, name=Gson Taro, noUse=null, target=Sun Mar 01 00:00:00 JST 2020], Person1 [age=3, name=Gson Taro, noUse=null, target=Wed Feb 12 00:00:00 JST 2020]]
------------------------------------------->

Next, an experiment to assign a character string to an Integer type

test.java


        StringBuilder jsonReader = new StringBuilder();
        jsonReader.append("[");
        jsonReader.append(" {\"age\":test,\"name\":\"Gson Taro\",\"target\":\"2020-02-10\"},");
        jsonReader.append(" {\"age\":2,\"name\":\"Gson Taro\",\"target\":\"2020-02-30\"},");
        jsonReader.append(" {\"age\":3,\"name\":\"Gson Taro\",\"target\":\"2020-02-12\"}");
        jsonReader.append("]");

[Failure]

I get a NumberFormatException.

Next, check the format that can be converted to Date type

test.java


        jsonReader.append("[");
        jsonReader.append(" {\"age\":1,\"name\":\"Gson Taro\",\"target\":\"2020-02-10\"},");
        jsonReader.append(" {\"age\":2,\"name\":\"Gson Taro\",\"target\":\"20200230\"},");
        jsonReader.append(" {\"age\":3,\"name\":\"Gson Taro\",\"target\":\"2020/02/12\"}");
        jsonReader.append("]");

[Failure]

Gson parses from the top line, left item on json, It raises an exception when the conversion fails. According to this experiment, in the case of "yyyy-MM-dd" and "yyyyMMdd" format, it is converted to a date, An exception will be thrown for "yyyy / MM / dd".

------------------------------------------->
Date input error: Failed to parse date["2020/02/12"]: Invalid number: _0
------------------------------------------->

Experiment with successful dates

test.java


        StringBuilder jsonReader = new StringBuilder();
        jsonReader.append("[");
        jsonReader.append(" {\"age\":1,\"name\":\"Gson Taro\",\"target\":\"2020-02-10\"},");
        jsonReader.append(" {\"age\":2,\"name\":\"Gson Taro\",\"target\":\"20200230\"},");
        jsonReader.append(" {\"age\":3,\"name\":\"Gson Taro\",\"target\":\"20200212\"}");
        jsonReader.append("]");

Click here for results

------------------------------------------->
Person1#toString: [Person1 [age=1, name=Gson Taro, noUse=null, target=Mon Feb 10 00:00:00 JST 2020], Person1 [age=2, name=Gson Taro, noUse=null, target=Sun Mar 01 00:00:00 JST 2020], Person1 [age=3, name=Gson Taro, noUse=null, target=Wed Feb 12 00:00:00 JST 2020]]
------------------------------------------->

Here, interestingly, 2020/2/30 is converted to 2020/3/1.

Let's read the source of this part Gson.

It is this part that is converted to Date. It looks like # L78). I think I can customize it here. .. ..

So, when I looked it up, in this part It seems that you can specify the date format. I will try using it.

test.java


        jsonReader.append("[");
        jsonReader.append(" {\"age\":1,\"name\":\"Gson Taro\",\"target\":\"2020-02-10\"},");
        jsonReader.append(" {\"age\":2,\"name\":\"Gson Taro\",\"target\":\"20200230\"},");
        jsonReader.append(" {\"age\":3,\"name\":\"Gson Taro\",\"target\":\"2020/02/12\"}");
        jsonReader.append("]");
        Gson gsonReader = new GsonBuilder().setDateFormat("yyyy/MM/dd").create();
        Type listType = new TypeToken<List<Person1>>(){}.getType();
        List<Person1> p1 = gsonReader.fromJson(jsonReader.toString(), listType);

        System.out.println("------------------------------------------->");
        System.out.println("Person1#toString: " + p1);
        System.out.println("------------------------------------------->");

The result is a successful perspective!

------------------------------------------->
Person1#toString: [Person1 [age=1, name=Gson Taro, noUse=null, target=Mon Feb 10 00:00:00 JST 2020], Person1 [age=2, name=Gson Taro, noUse=null, target=Sun Mar 01 00:00:00 JST 2020], Person1 [age=3, name=Gson Taro, noUse=null, target=Wed Feb 12 00:00:00 JST 2020]]
------------------------------------------->

Sounds good. Very easy to use! !!

Recommended Posts

I tried using Gson
I tried using TestNG
I tried using Galasa
I tried using azure cloud-init
I tried using Apache Wicket
I tried using Java REPL
I tried using anakia + Jing now
I tried using Spring + Mybatis + DbUnit
I tried using JOOQ with Gradle
I tried using Java8 Stream API
I tried using JWT in Java
[Android] I tried using Coordinator Layout.
I tried using Pari gp container
I tried using WebAssembly Stadio (2018/4/17 version)
I tried using Java memo LocalDate
I tried using GoogleHttpClient of Java
I tried Spring.
I tried tomcat
I tried youtubeDataApi.
I tried refactoring ①
I tried FizzBuzz.
I tried JHipster 5.1
I tried using Elasticsearch API in Java
I tried using Java's diagnostic tool Arthas
I tried using UICollectionViewListCell added from Xcode12.
I tried using Scalar DL with Docker
I tried using OnlineConverter with SpringBoot + JODConverter
It's new, but I tried using Groonga
I tried using OpenCV with Java + Tomcat
I tried using Docker for the first time
[I tried] Spring tutorial
[For beginners] I tried using DBUnit in Eclipse
I tried barcode scanning using Rails + React + QuaggaJS
I tried running Autoware
[For beginners] I tried using JUnit 5 in Eclipse
[Android] I quit SQLite and tried using Realm
I tried QUARKUS immediately
I made blackjack with Ruby (I tried using minitest)
I tried Spring Batch
[API] I tried using the zip code search API
I tried node-jt400 (Programs)
I tried node-jt400 (execute)
I tried to implement a server using Netty
I tried using the profiler of IntelliJ IDEA
I tried node-jt400 (Transactions)
I tried using a database connection in Android development
I tried using the Server Push function of Servlet 4.0
I tried using Alibaba Cloud's KMS (Key Management Service) service
I tried using Google Cloud Vision API in Java
I tried to operate SQS using AWS Java SDK
I tried using the Migration Toolkit for Application Binaries
I tried using Log4j2 on a Java EE server
I tried using YOLO v4 on Ubuntu and ROS
I tried using Docker Desktop for Windows on Windows 10 Home
I tried using an extended for statement in Java
I tried scraping a stock chart using Java (Jsoup)
I tried to build an environment using Docker (beginner)
I tried node-jt400 (Environment construction)
I tried DI with Ruby
I tried node-jt400 (IFS write)
Freeters everywhere tried using devise.