繁体   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