set date format in Gson in jsp

2019-06-10 03:36发布

问题:

I'm using Gson to convert Json to an object in Java. Json that i'm trying to convert has quite complicated structure.

{
   "name": "0",
   "dtExpiration": "07/14/2011 00:00",
   "quotaList": null,
   "question_array": [
      {
         "question": "0",
         "questionType": "resposta de texto",
         "min": "null",
         "max": "null",
         "responceList": [],
         "answer_array": [
            {
...

1.The question is: will gson.fromJson(json, SuperClass.class) work, as this class has ArrayLists?

I can't see if it works, because I have a problem with date format. The program throws exception:

Caused by: java.text.ParseException: Unparseable date: "07/15/2011 00:00"

So I had tried to specify format by using:

GsonBuilder gson = new GsonBuilder().setDateFormat("mm/dd/yyyy hh:mm");

but result is the same.

2.Can you explain me how to change date format using GsonBuilder?

Thank you

回答1:

1.The question is: will gson.fromJson(json, SuperClass.class) work, as this class has ArrayLists?

Yes, provided the SuperClass structure matches the JSON structure.

2.Can you explain me how to change date format using GsonBuilder?

Use big "M" for month in year. Small "m" is for minute in hour.

Here's a working example.

import java.io.FileReader;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new GsonBuilder().setDateFormat("MM/dd/yyyy hh:mm").create();

    SuperClass sc = gson.fromJson(new FileReader("input.json"), SuperClass.class);
    System.out.println(gson.toJson(sc));
    // {"name":"0","dtExpiration":"07/14/2011 12:00","question_array":[{"question":0,"questionType":"resposta de texto","min":"null","max":"null","responceList":[],"answer_array":[{"id":1,"answer":"yes"},{"id":2,"answer":"no"}]}]}
  }
}

class SuperClass
{
  String name;
  Date dtExpiration;
  List<String> quotaList;
  Question[] question_array;
}

class Question
{
  int question;
  String questionType;
  String min;
  String max;
  List<String> responceList;
  Answer[] answer_array;
}

class Answer
{
  int id;
  String answer;
}

Note that on my system, it changed from the 24H clock display to the 12H clock display.