ํ์
person.json ํ์ผ์ ์ ์ฅ๋ ์ฌ๋ ์ ๋ณด(์ด๋ฆ, ๋์ด ๋ฑ)์ ์ฝ์ด์ Person ๊ฐ์ฒด๋ก ๋ง๋๋ ์์ ์ค ๋ฐ์
์ฌ์ฉ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
Gson, FileInputStream
๊ธฐ์กด ์ฝ๋
public void readInfo() throws IOException {
final String filename = getFilesDir().getAbsolutePath() + "/person.json";
System.out.println(filename);
Gson gson = new Gson();
FileInputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
Arrays.fill(buffer, (byte)0);
fis.read(buffer);
String newStr = new String(buffer, StandardCharsets.UTF_8);
boolean isJson = isJSONValid(newStr); //JSON์ธ์ง ์๋์ง ๊ฒ์ฌํด์ ํต๊ณผ!
if(isJson)
{
System.out.println(newStr);
Person p = gson.fromJson(newStr, Person.class); //์ฃฝ๋ ์ง์
}
}
์๋ฌ ๋ก๊ทธ
use jsonreader.setlenient(true) to accept malformed json
ํด๊ฒฐ ๋ฐฉ๋ฒ
setlenient ์ฐพ๋ค๊ฐ ์๊ฐ์ ๋ ๋ ธ๋๋ฐ ๋์ ๊ฒฝ์ฐ์๋ byte์์ string์ผ๋ก ๋ณํํ ๋, (byte)0 ๊ฐ์ด ๊ทธ๋๋ก ๋ถ์ด ์์๋ค. string ๊ฐ์ ์ฐ์ด๋ณด๋ฉด "{ xxxxx }0000000" ์ด๋ ๊ฒ ๋ง์ด๋ค. ๊ทธ๋ฌ๋ gson์ ์ด์ฉํ์ฌ ๊ฐ์ฒด๋ก ๋ง๋ค ๋, ์๋ฌ๊ฐ ๋ฐ์ํ๋๊ฒ.
string ๊ฐ์ ์ฝ์ด์จ ํ, 0๊ฐ์ ์ ๊ฑฐํ ๋ค gson์ผ๋ก ๊ฐ์ฒด ๋ณํํ๋ ์ฑ๊ณต์ ์ผ๋ก ๋์๋ค.
ํด๊ฒฐ ์ฝ๋
static String trimZeros(String str) {
int pos = str.indexOf(0);
return pos == -1 ? str : str.substring(0, pos);
}
public void readInfo() throws IOException {
final String filename = getFilesDir().getAbsolutePath() + "/person.json";
System.out.println(filename);
Gson gson = new Gson();
FileInputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
Arrays.fill(buffer, (byte)0);
fis.read(buffer);
String newStr = new String(buffer, StandardCharsets.UTF_8);
newStr = trimZeros(newStr); //์ถ๊ฐ๋ ์ฝ๋
boolean isJson = isJSONValid(newStr);
if(isJson)
{
System.out.println(newStr);
Person p = gson.fromJson(newStr, Person.class);
}
}
๋๊ธ