簡體   English   中英

子類對象的Java JSON解析

[英]Java JSON parsing for subclass objects

我能夠寫入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;
    }

事件類:

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();
        }


}

您只需通過傳遞Events列表來調用方法toJson ,該Events列表包含可以是TimedEventFloatingEvent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM