如何在Android中将自定义对象转换为String?

时间:2013-05-14 12:32:18

标签: java android object serialization

我有一个自定义类的Object。我需要将它转换为String,以便我可以将其写入文件。有没有办法解决这个问题?

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您无法自动将自定义类转换为String。系统无法知道您希望如何格式化String,确切地想要在其中进行格式化等等。

您必须在自定义类中手动实现一个方法,该方法返回对象的文本解释。通常,您会覆盖名为toString()的方法。如果您为某些方法提供类的实例,则通常会自动调用此方法。假设您执行System.out.println(instance),则会自动调用instance的{​​{1}}方法。

我不知道你的自定义类是什么。但是,让我们说它类似于toString()类,其中包含成员变量PersonString name。然后,类中定义的int age方法看起来像这样:

toString()

这将提供类似“名称:某些名称,年龄:30”的输出。

答案 1 :(得分:0)

尝试使用objectname.toString()方法。

答案 2 :(得分:0)

将serialize对象转换为String并将String转换为Object

public static String beanToString(Object object) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    StringWriter stringEmp = new StringWriter();
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.writeValue(stringEmp, object);
    return stringEmp.toString();
}

public static <T> T stringToBean(String content, Class<T> valueType) throws IOException {
    return new ObjectMapper().readValue(content, valueType);
}

将对象保存到文件

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();