我不知道如何在此之后将我的Java转换为JSON与Jackson
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper mapper = new ObjectMapper();
Book b = new Book();
ArrayList<Book> listBook = new ArrayList<Book>();
listBook.add(b);
b = new Book();
b.setName("exam");
b.setFileName("res/raw/exam.txt");
b.setCate(0); //4 categories here
b.setSoundFileName("res/raw/exams.mp3");
b.setTranFileName("res/raw/examt.txt");
listBook.add(b);
b = new Book();
b.setName("test");
b.setCate(0);
b.setFileName("res/raw/test.txt");
b.setSoundFileName("res/raw/tests.mp3")
b.setTranFileName("res/raw/textt.txt");
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(listBook);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ttt", "show ans : "+jsonString);
下一步如何将此内容写入SD卡?
答案 0 :(得分:0)
正如用户Zain所说,Gson使用起来更方便,但是,假设您从这一行获取Json字符串:
jsonString = mapper.writeValueAsString(listBook);
然后使用此方法将字符串写入sdcard中的文件。
public static void writeStringToFile(String p_string, String p_fileName)
{
FileOutputStream m_stream = null;
try
{
m_stream = new FileOutputStream(p_fileName);
m_stream.write(p_string.getBytes());
m_stream.flush();
}
catch (Throwable m_th)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_th);
}
finally
{
if (m_stream != null)
{
try
{
m_stream.close();
}
catch (Throwable m_e)
{
Log.e(TAG + " Error in writeStringToFile(String p_string, String p_fileName) of FileIO", m_e);
}
m_stream = null;
}
}
}