0

I have a text field where user can enter data, once data is received i want to append it to existing JSON file.

I am able to read the existing data and getting the text field value, but while appending the new data with existing data I'm facing problem.

Error:

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $

Below code :

JSON File :

{"vins":[{"vin":"544554"},{"vin":"54554"}]}

Text field value : String test ="3689"; so it should be appended as :

{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}

Filereadwrite class :

public class JSONFIlewrite {
    public static String Vinno_Read;
    public static List<String> linststring;
    public static void main(String[] args) {
        try {

            JSONParser parser = new JSONParser();
            Object obj = parser.parse(new 
            FileReader("C:\\Amaresh\\Test\\sample_json.json"));

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject);
            linststring= new ArrayList();
            // loop array
            JSONArray msg = (JSONArray) jsonObject.get("vins");
            Iterator iterator = msg.iterator();

            while (iterator.hasNext()) {
                Vinno_Read = iterator.next().toString();

                linststring.add(Vinno_Read);


            }

            String list_string = "";
            System.out.println(linststring);

            for(String temp:linststring){
                list_string += temp;
                System.out.println("amar1"+list_string);
            }

            System.out.println("amar"+list_string);
            Vin vin4 = new Vin();
            vin4.setVin("76354273462");
            Vins vins = new Vins();
            vins.addVins(vin4);

            Gson gson = new Gson();
            //String jsonValue=list_string;

            String jsonValue = gson.toJson(list_string).toString();
            System.out.println("json--"+jsonValue);
            Vins vins1 = gson.fromJson(jsonValue, Vins.class);
            System.out.println("ddd"+vins1);
            Vin vin = new Vin();
            vin.setVin("544554");

            vins1.addVins(vin);

            jsonValue = gson.toJson(vins1).toString();

            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new FileWriter("C:\\Amaresh\\Test\\sample_json.json"));
                writer.write(jsonValue);
                System.out.println("Test"+jsonValue);

            } catch (IOException e) {
            } finally {
              try {
                if (writer != null)
                    writer.close();
              } catch (IOException e) {
            }
        }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Setter Getter classes :

public class Vin {
    @Expose
    private String vin;

    public String getVin() {
        return vin;
    }

public void setVin(String vin) {
    this.vin = vin;
}

}


public class Vins {
    @Expose
    List<Vin> vins = new ArrayList<>();

    public List<Vin> getVins() {
        return vins;
    }

    public void addVins(Vin vin) {
        this.vins.add(vin);
    }
}
4
  • What is the problem you are facing? Commented Jun 9, 2017 at 18:14
  • if i comment line //String jsonValue = gson.toJson(list_string).toString(); and pass this value String jsonValue=list_string; which i am reading from file error i am getting below error {"vins":[{"vin":"544554"},{"vin":"54554"}]} [{"vin":"544554"}, {"vin":"54554"}] amar1{"vin":"544554"} amar1{"vin":"544554"}{"vin":"54554"} amar{"vin":"544554"}{"vin":"54554"} json--{"vin":"544554"}{"vin":"54554"} com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $ Commented Jun 9, 2017 at 18:42
  • i am not getting how the new text field value i will append to existing data than write. Please help. Commented Jun 9, 2017 at 18:46
  • what library are you using ? since JSONParser is actually defined as JsonParser in GSON library google.github.io/gson/apidocs/com/google/gson/JsonParser.html Commented Jun 9, 2017 at 19:11

2 Answers 2

1

Main Logic:

you can see 4 blocks in the code

  1. Reading the json file and parsing to a java Object
  2. Casting de java Object to a JSonObject, parsing to a JsonArray and iterating the array printing the JsonElements
  3. Creating a new Vin Object and converting it to a JSON String using Gson.toJson method (2nd part is not required only illustrative purposes)
  4. Creating a JsonWriter, creating a Vins Object and loading it with the original JsonArray and then adding a new element (that correspondents to the new Vin Object created in step #3, finally writing the Vins Object to the [new] file.

Input:

{"vins":[{"vin":"544554"},{"vin":"54554"}]}

Output:

{"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]}

Code

import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;

public class JSONFIlewrite {
    public static String Vinno_Read;
    public static List<String> linststring;

    public static void main(String[] args) {
        try {

            JsonParser parser = new JsonParser();
            Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json"));



            JsonObject jsonObject = (JsonObject) obj;
            System.out.println(jsonObject);
            linststring = new ArrayList<String>();
            // loop array
            JsonArray msg = (JsonArray) jsonObject.get("vins");
            Iterator<JsonElement> iterator = msg.iterator();
            while (iterator.hasNext()) {
                Vinno_Read = iterator.next().toString();
                System.out.println("Vinno_Read---->" + Vinno_Read);
            }



            Vin newVin = new Vin();
            newVin.setVin("3689");
            Gson gson = new Gson();
            String json = gson.toJson(newVin);
            System.out.println("json---->" + json);



            FileWriter file = new FileWriter("C:\\Amaresh\\Test\\sample_json2.json", false);
            JsonWriter jw = new JsonWriter(file);
            iterator = msg.iterator();
            Vins vins = new Vins();
            while (iterator.hasNext()) {
                vins.addVin(gson.fromJson(iterator.next().toString(), Vin.class));
            }
            vins.addVin(newVin);
            gson.toJson(vins, Vins.class, jw);
            file.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Notes:

Since I don't know what library you are using, I have updated the class names to be compatible to GSON.

I have also changed the method: public void addVins(Vin vin) in Vins Class to public void addVin(Vin vin)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, Its working. I have one question if user enters a text data which is already present say Vin : 3689 already exist than i don't want to write duplicate entries to file how to achieve it.
For that, in the 4 step, you need to ask IF the array CONTAINS already the new Vin , IF it does then skipping it ELSE then go ahead and adding the new Vin. So, now is your turn for coding it :)
I meant the ArrayList inside the Vins object.
1

To keep the existing content and append the new content to the end of JSON file:

Example1:

new FileWriter(file,true);

or you can try example02:

FileWriter file= new FileWriter(JSONLPATH,true)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.