0

I been trying to solve this issue for quite a while now but i don't seem to have anymore route to take.

I had some backslash that i managed to remove with replace("\", "") but i still have some Quotation Mark like this one ---> " just in the beginning of my map and I don't have any idea how it gets there.

Here is my code:

        public void actionPerformed(ActionEvent e) {
            JsonObject obj = new JsonObject();
            JsonArray ingredList = new JsonArray();
            Map<String, String> ingredientAsMap = new HashMap<>();
            JsonArray prepTime = new JsonArray();
            Map<String, String> prepTimeAsMap = new HashMap<>();
            JsonArray cookTime = new JsonArray();
            Map<String, String> cookTimeAsMap = new HashMap<>();

            obj.addProperty("Recipe Name", textField1.getText().toString());
            for (int r = 0; r < model.getRowCount(); r++) {
                ingredientAsMap.put("Ingredient", model.getValueAt(r, 0).toString());
                ingredientAsMap.put("Measure", model.getValueAt(r, 1).toString());
                ingredientAsMap.put("Quantity", model.getValueAt(r, 2).toString());
                ingredList.add(String.valueOf(ingredientAsMap));
            }

            obj.addProperty("Ingredients Lists", String.valueOf(ingredList));
            obj.addProperty("Preparation", editorPane1.getText().toString());
            prepTimeAsMap.put("Hours", spinner3.getValue().toString());
            prepTimeAsMap.put("Mins", spinner2.getValue().toString());
            prepTime.add(String.valueOf(prepTimeAsMap));
            obj.addProperty("Preparation Time", String.valueOf(prepTime));

            cookTimeAsMap.put("Hours", spinner1.getValue().toString());
            cookTimeAsMap.put("Mins", spinner4.getValue().toString());
            cookTime.add(String.valueOf(cookTimeAsMap));
            obj.addProperty("Cooking Time", String.valueOf(cookTime));

            Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
            String json = gson.toJson(obj).replace("\\", "");
            try{
                FileWriter writer = new FileWriter(System.getProperty("user.dir") + "\\" + textField1.getText().toString() + ".json");
                BufferedWriter bw = new BufferedWriter(writer);

                bw.write(json);
                bw.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            System.out.println(json);
            //System.out.println(System.getProperty("user.dir") + "\\" + textField1.getText().toString() + ".json");
        }

Here is the output I get when my form is filled:

    {
  "Recipe Name": "Test",
  "Ingredients Lists": "["{Ingredient=Ingredient0, Measure=ml, Quantity=0}","{Ingredient=Ingredient1, Measure=ml, Quantity=0}"]",
  "Preparation": "This is a test.",
  "Preparation Time": "["{Hours=0, Mins=0}"]",
  "Cooking Time": "["{Hours=0, Mins=0}"]"
    }

Notice the " before the [ in Ingredient List, Preparation Time and Cooking Time. How do I get rid of them?

Thanks in advance!

1 Answers1

1

Your issue starts with lines like these

obj.addProperty("Ingredients Lists", String.valueOf(ingredList));
obj.addProperty("Preparation Time", String.valueOf(prepTime));

For the HashMaps, refer How to convert hashmap to JSON object in Java (not the accepted one, but the Gson answer)

Similarly, for the JSONArray, you don't need to String.value them. Just add directly. From the API, use the add(String name, JsonElement element) method.

obj.add("Preparation Time", prepTime);

Detailed answer

Stop string replacing. Your internal data sets are just not JSON, so you are building that JSON incorrectly.

Notice the syntax highlighting

Invalid

{ "Preparation Time": "["{Hours=0, Mins=0}"]" }

Valid - The inner string is escaped.

{ "Preparation Time": "[\"{Hours=0, Mins=0}\"]" }

Which is essentially seen as this to any JSON parser

{ "Preparation Time": "..." }

You can getString("Preparation Time"), and it returns "[\"{Hours=0, Mins=0}\"]" as a String. If you convert that to a JSONArray, then it's an array of strings. Print the first element, you should only see "{Hours=0, Mins=0}" (quotes are kept), and so you should be replacing the quotes and {} characters, not the backslashes. And you could split on equal signs to get key-values, and etc,etc... but that sounds like a lot of work.


Basically, there are no equal signs in key-value JSON pairs.

{Ingredient=Ingredient0, Measure=ml, Quantity=0}

So, Gson is doing to treat every single one of those keys's values as String type and any quotes or backslashes are going to be unescaped when you print the data, but it is stored in memory escaped.

However you want to parse the extra data is unrelated to JSON parsing, so that is my hint and you can stop scratching your head hopefully.


For what it's worth, here is JSON for that data. So, my suggestion is to fix the model class and pieces of code that generate this data.

{
    "Recipe Name": "Test",
    "Ingredients Lists": [{
        "Ingredient": "Ingredient0",
        "Measure": "ml",
        "Quantity": 0
    }, {
        "Ingredient": "Ingredient1",
        "Measure": "ml",
        "Quantity": 0
    }],
    "Preparation": "This is a test.",
    "Preparation Time": [{
        "Hours": 0,
        "Mins": 0
    }],
    "Cooking Time": [{
        "Hours": 0,
        "Mins": 0
    }]
}
Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245