1

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 Answer 1

4

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.

2
  • I had changed it, but getting the same exception! am i doing right: 1st i'm creating Gson object, then setting date format as specified above(with "M" this time) and then trying to convert json?
    – andriy
    Jul 14, 2011 at 16:08
  • thank you very much! I was almost there.. when I was doing Gson gson = new GsonBuilder(), was getting incompatible types error
    – andriy
    Jul 14, 2011 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.