How to write to a.json file

Asked

Viewed 1,116 times

0

I have some files .json in assets.

inserir a descrição da imagem aqui


I am currently reading only in these files.

Reading

public String loadJSONFromAsset(String Ajson) {
    String json = null;
    try {
        InputStream is = context.getAssets().open(Ajson);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }

    return json;
}

How can I write on them? That is, replace all their content with another of my choice.

1 answer

1

Cristian,

The ideal would be to use a JSON parser that will make it easier to manipulate this modified object than to simply edit the text of the file.

On the official website you can find several packages http://www.json.org/

Download a package, for example: https://github.com/stleary/JSON-java

Import to your project and follow the example of usage:

import org.json.JSONObject;

//instancia um novo JSONObject
JSONObject my_obj = new JSONObject();

//preenche o objeto com os campos: titulo, ano e genero
my_obj.put("titulo", "JSON Parser Exemplo");
my_obj.put("ano", 2017);
my_obj.put("genero", "Programação");

This will make it easier for you to edit your json. More information:

http://www.devmedia.com.br/trabalhando-com-json-em-java-o-pacote-org-json/25480


I hope this helps...

Good Luck!

  • Nice, but I need to do this for the Java language, because I will consume from an API the new json script to replace with the old one in the file that is in Assets.

  • It would take the new json of the API and place this json in a String, replace the existing content in the.json file with the content of this String.

  • I reworked the answer, did it help you? Did it? Would you also like to know the writing process of the altered json? Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.