简体   繁体   中英

Java “settings object”, serialization/deserialization

( Code is for Android Actually, I need code to be portable between Android and Java SE.)

I want to have a "settings" class with various game settings, like

public int map_size;
public String server_name;

etc.

The data needs to be accessed fairly frequently (so members, not a key-value map), and from time to time de/serialized in some standard way (mainly to send it through network).

I want to be able to

  1. Serialize and deserialize the object into XML or JSON, without having to explicitly write the code for every member (but still having some degree of control over the format).

  2. Define some (constant) meta-data about every member (default value, GUI name, XML identifier, ...), in a way that allows for easy modification in the source code (I want to be able to add a new meta-property, define a default value for it, and not have to specify it everywhere else).

1 is achievable by using reflection. I thought Java annotations for class members would be perfect for 2:

@Setting(id = "server_name", name = "Server title", default = "Server0")
public String server_name;

But it looks like (user-defined) annotations don't work in Android yet - code using them crashes the compiler...

(or another way to approach all this)? (或其他方法来解决所有这些问题) 什么?

  • Store information about settings in some external XML file?

  • Store it in a Java data structure, with content defined in the code? Defining the data in this way somehow seems very unwieldy, especially compared to keyword arguments of annotations.

  • ?

FYI, it looks like Jackson was fixed to work with Android in the Jackson 0.9.7 release.

Though I agree with Daniel Lew that using the built-in Android preferences is the best solution for an Android client. For a JavaSE client the Properties class is a good way to store preferences. There's also a JavaSE preferences package, but it may do more then you need.

Is there any particular reason you're not using built-in Android preferences ? As long as all the game settings are primitives (or Strings) then that's probably the easiest way to store preferences. Also, it synchronizes well with PreferenceActivity if you end up making a settings page (there are some Preference examples in the ApiDemos).

While I'm not sure how well they work on Android, XStream or Jackson provide highly customizable XML or JSON (de)serialization of Java objects. Note that XStream supports both XML and JSON output, Jackson is just JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM