SoFunction
Updated on 2025-04-13

Examples and instructions for parsing JSON data code in Java

Example parsing the following JSON data

 {"code":0,
   "msg":"success",
   "data":            
 [{
"host":"",
"port":"",
"m_token":"490e20e70e7de5f21a24b14c12a393f6",
"category":"sd",
"sub_category":"M1049",
"flyback_date":"2025-02-17",
"versions":["0.4.2"],
"req_times":["2025-02-15 02:58:20"],
"create_time":"2025-02-18 06:58:20",
"update_time":"2025-02-18 06:58:20"}]
}

The following is a Gson library as an example to show how to parse this JSON data:

First, we need to introduce dependencies of the Gson library into the project. If using the Maven project, you canAdd the following dependencies to the file:

<dependency>
    <groupId></groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Next, define the corresponding Java class to map the JSON data structure:

import ;

public class ResponseData {
    private int code;
    private String msg;
    private List<DataItem> data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
         = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
         = msg;
    }

    public List<DataItem> getData() {
        return data;
    }

    public void setData(List<DataItem> data) {
         = data;
    }

    public static class DataItem {
        private String host;
        private String port;
        private String m_token;
        private String category;
        private String sub_category;
        private String flyback_date;
        private List<String> versions;
        private List<String> req_times;
        private String create_time;
        private String update_time;

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
             = host;
        }

        public String getPort() {
            return port;
        }

        public void setPort(String port) {
             = port;
        }

        public String getM_token() {
            return m_token;
        }

        public void setM_token(String m_token) {
            this.m_token = m_token;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
             = category;
        }

        public String getSub_category() {
            return sub_category;
        }

        public void setSub_category(String sub_category) {
            this.sub_category = sub_category;
        }

        public String getFlyback_date() {
            return flyback_date;
        }

        public void setFlyback_date(String flyback_date) {
            this.flyback_date = flyback_date;
        }

        public List<String> getVersions() {
            return versions;
        }

        public void setVersions(List<String> versions) {
             = versions;
        }

        public List<String> getReq_times() {
            return req_times;
        }

        public void setReq_times(List<String> req_times) {
            this.req_times = req_times;
        }

        public String getCreate_time() {
            return create_time;
        }

        public void setCreate_time(String create_time) {
            this.create_time = create_time;
        }

        public String getUpdate_time() {
            return update_time;
        }

        public void setUpdate_time(String update_time) {
            this.update_time = update_time;
        }
    }
}

Then, use the Gson library to parse the JSON data:

import ;
import ;
import ;
import ;
import ;

class ResponseData {
    private int code;
    private String msg;
    private List&lt;DataItem&gt; data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
         = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
         = msg;
    }

    public List&lt;DataItem&gt; getData() {
        return data;
    }

    public void setData(List&lt;DataItem&gt; data) {
         = data;
    }

    static class DataItem {
        private String host;
        private String port;
        private String m_token;
        private String category;
        private String sub_category;
        private String flyback_date;
        private List&lt;String&gt; versions;
        private List&lt;String&gt; req_times;
        private String create_time;
        private String update_time;

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
             = host;
        }

        public String getPort() {
            return port;
        }

        public void setPort(String port) {
             = port;
        }

        public String getM_token() {
            return m_token;
        }

        public void setM_token(String m_token) {
            this.m_token = m_token;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
             = category;
        }

        public String getSub_category() {
            return sub_category;
        }

        public void setSub_category(String sub_category) {
            this.sub_category = sub_category;
        }

        public String getFlyback_date() {
            return flyback_date;
        }

        public void setFlyback_date(String flyback_date) {
            this.flyback_date = flyback_date;
        }

        public List&lt;String&gt; getVersions() {
            return versions;
        }

        public void setVersions(List&lt;String&gt; versions) {
             = versions;
        }

        public List&lt;String&gt; getReq_times() {
            return req_times;
        }

        public void setReq_times(List&lt;String&gt; req_times) {
            this.req_times = req_times;
        }

        public String getCreate_time() {
            return create_time;
        }

        public void setCreate_time(String create_time) {
            this.create_time = create_time;
        }

        public String getUpdate_time() {
            return update_time;
        }

        public void setUpdate_time(String update_time) {
            this.update_time = update_time;
        }
    }
}

public class JsonParsingExample {
    public static void main(String[] args) {
        String json = "{\"code\":0,\"msg\":\"success\",\"data\":[{\"host\":\"\",\"port\":\"\",\"m_token\":\"490e20e70e7de5f21a24b14c12a393f6\",\"category\":\"sd\",\"sub_category\":\"M1049\",\"flyback_date\":\"2025-02-17\",\"versions\":[\"0.4.2\"],\"req_times\":[\"2025-02-15 02:58:20\"],\"create_time\":\"2025-02-18 06:58:20\",\"update_time\":\"2025-02-18 06:58:20\"}]}";

        Gson gson = new Gson();
        ResponseData response = (json, );

        ("Code: " + ());
        ("Message: " + ());

        for ( item : ()) {
            ("Host: " + ());
            ("Port: " + ());
            ("m_token: " + item.getM_token());
            ("Category: " + ());
            ("Sub Category: " + item.getSub_category());
            ("Flyback Date: " + item.getFlyback_date());
            ("Versions: " + ());
            ("Req Times: " + item.getReq_times());
            ("Create Time: " + item.getCreate_time());
            ("Update Time: " + item.getUpdate_time());

            if (!item.getReq_times().isEmpty()) {
                String firstReqTime = item.getReq_times().get(0);
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = (firstReqTime);
                    long timestamp = ();
                    ("First Req Time Timestamp: " + timestamp);
                } catch (ParseException e) {
                    ("Failed to parse date: " + firstReqTime);
                    ();
                }
            }
        }
    }
}

The above code first defines the Java class corresponding to the JSON data structure, and then uses the Gson library to parse the JSON string into a Java object and prints out the parsed data. If you use the Jackson library, the parsing process will be different, but the principles are similar.

Will parse outreq_timesThe first time string in the list is converted to a timestamp. In Java, you can useSimpleDateFormatClass to parse datetime strings and convert them toDateObject, then passDateThe object'sgetTime()Method gets the corresponding timestamp.

Code description:

  • Date formatting:useSimpleDateFormatClass, its constructor is passed in"yyyy-MM-dd HH:mm:ss"As a format template for datetime, this template matches the datetime string format in JSON data.
  • Parsing date strings: CallSimpleDateFormatThe object'sparse()Method parses the date and time string intoDateObject.
  • Get the timestamp:passDateThe object'sgetTime()Method gets the corresponding timestamp (from 00:00:00 UTC on January 1, 1970 to the milliseconds of that date).
  • Exception handling:usetry-catchBlock CaptureParseExceptionException. When the date and time string format does not match the template, the exception will be thrown, and the error message will be printed after being caught and the stack trace will be output.

Run the above code and outputReq TimesAfter the information, an additional time stamp corresponding to the first request time will be output.

Summarize

This is the end of this article about parsing JSON data code in Java. For more related Java parsing JSON data content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!