用于子类对象的Java JSON解析

时间:2014-03-17 08:34:38

标签: java json gson

我可以写入JSON文件。为什么如果我从另一个子类中编写另一个对象,JSON文件将被重写,只显示该新子类的字段....之前的条目将被删除...

示例:

//evt is an ArrayList<Event> list
//evt contains a list of objects of type TimedEvent
//TimedEvent extends Event class
//Event is the abstract class
toJson("C://myJson.json", evt); 

以上将产生这个:

[
  {
    "eventStartDateTime": {
      "year": 2014,
      "month": 3,
      "dayOfMonth": 11,
      "hourOfDay": 11,
      "minute": 5,
      "second": 0
    },
    "eventEndDateTime": {
      "year": 2014,
      "month": 3,
      "dayOfMonth": 11,
      "hourOfDay": 12,
      "minute": 5,
      "second": 0
    },
    "title": "My First Event",
    "eventId": "2u0-zBGhkdX8FcbFCFp3ah",
    "completed": false
  }
]

但是如果我将列表更改为不同子类中的其他对象,则第一个JSON文件中的先前字段将消失。

//evt is an ArrayList<Event> list
//evt this time contains a list of objects of type FloatingEvent
//FloatingEvent also extends Event class
toJson("C://myJson.json", evt);

以上将产生这个:

[
  {
    "title": "My First Event",
    "eventId": "2u0-zBGhkdX8FcbFCFp3ah",
    "completed": false
  },
  {
    "title": "My Second Event",
    "eventId": "19Jv07-a4ICaex.8fceZOc",
    "completed": false
  }
]

如何确保方法toJson附加新事件,但保留第一次写入的任何字段。

我需要的是这样的东西..可能吗?? ....如何在检索时将两个对象分开?

[
  {
    "eventStartDateTime": {
      "year": 2014,
      "month": 3,
      "dayOfMonth": 11,
      "hourOfDay": 11,
      "minute": 5,
      "second": 0
    },
    "eventEndDateTime": {
      "year": 2014,
      "month": 3,
      "dayOfMonth": 11,
      "hourOfDay": 12,
      "minute": 5,
      "second": 0
    },
    "title": "My First Event",
    "eventId": "2u0-zBGhkdX8FcbFCFp3ah",
    "completed": false
  },
  {
    "title": "My Second Event",
    "eventId": "19Jv07-a4ICaex.8fceZOc",
    "completed": false
  }
]

我用来编写JSON文件的代码:

public static String toJson(String fileName, List<Event> evt) {
    fileName = Utilities.getDefaultFileName();

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    String json = "";

    try {
        File file = new File(fileName);

        // if file does not exists, then create it
        if (!file.exists()) {
            json = gson.toJson(evt);
            file.createNewFile();
            FileWriter writer = new FileWriter(fileName);
            writer.write(json);
            writer.close();
        } else {
            ArrayList<Event> currentEventList = fromJson(fileName);
            for (Event newEvent : evt) {
                currentEventList.add(newEvent);
            }
            json = gson.toJson(currentEventList);

            file.delete();
            file.createNewFile();
            FileWriter writer = new FileWriter(fileName);
            writer.write(json);
            writer.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.out.println(Language.getString("ERROR_CONVERT_DATA_OBJECT"));
    }
    return fileName;
}

我用来从JSON文件中检索事件列表的代码:

public static ArrayList<Event> fromJson(String fileName) {
        ArrayList<Event> list = new ArrayList<Event>();
        try {
            Gson gson = new Gson();
            Event[] myTypes = gson.fromJson(new FileReader(fileName),
                    Event[].class);
            for (int i = 0; i < myTypes.length; i++) {
                list.add(i, myTypes[i]);
            }

        } catch (JsonSyntaxException e) {

            e.printStackTrace();
        } catch (JsonIOException e) {

            e.printStackTrace();
        } catch (FileNotFoundException e) {

            System.out
                    .println(Language.getString("ERROR_MISSING_DEFAULT_FILE"));
        }
        return list;
    }

Event类:

public  class Event {
  protected String title;
  protected String eventId;
  protected String eventDescription;

  protected boolean completed;

  // 
  public Event() {
    setEventId();
    completed = false;
  }

  // 
  public String getEventId() {
    return eventId;
  }

  public void setEventId() {
    this.eventId=Utilities.generateUniqueIdentification();
  }

  // 
  public String getEventDescription() {
    return eventDescription;
  }

  public void setEventDescription(String eventDescription) {
    this.eventDescription = eventDescription;
  }

  // 
  public boolean getCompleted() {
    return completed;
  }

  // 
  public void setCompleted() {
    completed = true;
  }

  // 
  public void setUncompleted() {
    completed = false;
  }

  // 
  /**
   * This method returns the title of an event.
   * @return Returns event title.
   */
  public String getTitle() {
    return title;
  }

  // 
  /**
   * This method sets the title of an event.
   * @param title The title of this event.
   */
  public void setTitle(String title) {
    this.title = title;
  }

}

TimedEvent类:

import java.util.Calendar;


public class TimedEvent extends Event {
        protected Calendar eventStartDateTime;
        protected Calendar eventEndDateTime;


        public TimedEvent(String title, Calendar eventStartDateTime,
                        Calendar eventEndDateTime) {
                super();

                this.title = title;
                this.eventStartDateTime = eventStartDateTime;
                this.eventEndDateTime = eventEndDateTime;
        }


        public Calendar getEventStartDateTime() {
                return eventStartDateTime;
        }


        public void setEventStartDateTime(Calendar eventStartDateTime) {
                this.eventStartDateTime = eventStartDateTime;
        }


        public Calendar getEventEndDateTime() {
                return eventEndDateTime;
        }


        public void setEventEndDateTime(Calendar eventEndDateTime) {
                this.eventEndDateTime = eventEndDateTime;
        }

}

FloatingEvent类:

public class FloatingEvent extends Event{

        //
        public FloatingEvent(String title){
                super();
                setTitle(title);
                setEventId();
        }


}

1 个答案:

答案 0 :(得分:0)

您只需调用方法toJson一次,方法是传递包含EventsTimedEvent对象的FloatingEvent列表。