mak_doni
mak_doni

Reputation: 581

How to save data with gson in a json file?

In my web application I succeed in displaying data in html table using mybatis. Now I want to save the records of the Mysql table in a json file and create an array of users, I used Gson, the problem is that just one record saved in the file. Thanks.
Here the result in file.json:

{"data":
 [
 {"id":2,"Name":"Mike"}
 ]
}

servlet.java

SqlSession session = MyBatisSqlSessionFactory.getSession();
List<User> users = session.selectList("dao.UserDao.findAll");
for (User u : users) {
    Gson gson = new Gson();
    try {
        JsonWriter  writer = new JsonWriter(new FileWriter("C:\\file.json"));
        writer.beginObject();
        writer.name("data");
        writer.beginArray();
        writer.beginObject();
        writer.name("id").value(t.getId());
        writer.name("name").value(t.getNom());
        writer.endObject();
        writer.endArray();
        writer.endObject();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

session.close();

Upvotes: 32

Views: 79075

Answers (3)

nessa.gp
nessa.gp

Reputation: 1864

Quick fix to your code:

SqlSession session = MyBatisSqlSessionFactory.getSession();
List<User> users = session.selectList("dao.UserDao.findAll");
try {
    JsonWriter writer = new JsonWriter(new FileWriter("C:\\file.json"));
    writer.beginObject();
    writer.name("data");
    writer.beginArray();
    for (User u : users) {
        writer.beginObject();
        writer.name("id").value(t.getId());
        writer.name("name").value(t.getNom());
        writer.endObject();
    }
    writer.endArray();
    writer.endObject();
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

However, in the case that your User class looks like this:

public class User {
    String id;
    String name;
}

Then you don't need to code the adapter as Gson is able to automatically generate the JSON code for a class that only has primitives (ints, Strings, etc.). So your code would look as @roy-shmuli but only if you omit the data and keep only the array as List can be completely generated without an adapter. The JSON code generated would look like this:

[
    {"id":1, "name": "Mike"},
    {"id":2, "name": "Lucy"}
]

Hope it helps to the beginners.

Upvotes: 2

sonavolob
sonavolob

Reputation: 354

I was previously using outputStream.writeObject and Serializable with default writer/reader for saving object data. Because of problems with code sustainability I have been after something else. This is the result. That BufferedWriter is mandatory, otherwise write speed drops 8 times. Notice that UTF-8 declaration which is default encoding of Json. Not sure whether not declaring it is safe.

Example:

private void saveJson(Object object, Type type, String directory, String fileName) {

    File file = new File(getApplicationContext().getDir(directory, Context.MODE_PRIVATE),
            fileName);
    OutputStream outputStream = null;
    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting()
            .create();
    try {
        outputStream = new FileOutputStream(file);
        BufferedWriter bufferedWriter;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,
                    StandardCharsets.UTF_8));
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        }

        gson.toJson(object, type, bufferedWriter);
        bufferedWriter.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        if (DEBUG) Log.e(saveJson, "saveUserData, FileNotFoundException e: '" + e + "'");
    } catch (IOException e) {
        e.printStackTrace();
        if (DEBUG) Log.e(saveJson, "saveUserData, IOException e: '" + e + "'");
    } finally {
        if (outputStream != null) {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                if (DEBUG) Log.e(saveJson, "saveUserData, finally, e: '" + e + "'");
            }
        }
    }

}


private Object loadJson(Type type,  String directory, String fileName) {
    Object jsonData = null;

    File file = new File(getApplicationContext().getDir(directory, Context.MODE_PRIVATE),
            fileName);
    InputStream inputStream = null;
    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting()
            .create();
    try {
        inputStream = new FileInputStream(file);
        InputStreamReader streamReader;
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            streamReader = new InputStreamReader(inputStream,
                    StandardCharsets.UTF_8);
        } else {
            streamReader = new InputStreamReader(inputStream, "UTF-8");
        }

        jsonData = gson.fromJson(streamReader, type);
        streamReader.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        if (DEBUG) Log.e(TAG, "loadJson, FileNotFoundException e: '" + e + "'");
    } catch (IOException e) {
        e.printStackTrace();
        if (DEBUG) Log.e(TAG, "loadJson, IOException e: '" + e + "'");
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                if (DEBUG) Log.e(TAG, "loadJson, finally, e: '" + e + "'");
            }
        }
    }
    return jsonData;
}

where Type for example:

Type type = new TypeToken<Map<String, Object>>() { }.getType();

Upvotes: 5

Roy Shmuli
Roy Shmuli

Reputation: 5019

You write all the users in same file C:\\file.json so just the last iteration of the loop saved.

You can convert the object List<User> into json and write it once (no needed loop)

Example:

try (Writer writer = new FileWriter("Output.json")) {
    Gson gson = new GsonBuilder().create();
    gson.toJson(users, writer);
}

Upvotes: 78

Related Questions