0

I am getting String jsonObject in my controller. The structure is following:

{ "cats":
    [
        {
  "name": "Smoky",
  "age": 12,
  "color": "gray"
},
        {
  "name": "Oscar",
  "age": 3,
  "color": "black"
},
       {
  "name": "Max",
  "age": 4,
  "color": "white"
}
    ]
}

I need to parse it into String[] jsonObjects or List<String> jsonObjects.
Using GSON I am trying to do it this way:

public static String[] toArray(String json) {
        final String PARSING_ERROR = "Error while parsing json to string array";
        try {
            JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
            String tableName = jsonObject.keySet().toArray()[0].toString();
            JsonArray jsonArray = jsonObject.getAsJsonArray(tableName);
            String[] strings = new String[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                String stringJson = jsonArray.get(i).toString();
                strings[i] = stringJson;
            }
            return strings;
        } catch (Exception e) {
            System.err.println(PARSING_ERROR);
            throw new DataException(PARSING_ERROR);
        }
    }

It works, but after parsing I recieve the following String:

{"name":"Smoky","age":12,"color":"gray"}

How can I get the String in the following format:

{
  "name": "Smoky",
  "age": 12,
  "color": "gray"
}
5
  • if you want just format this string see stackoverflow.com/questions/11020894/… Commented Feb 10, 2019 at 19:36
  • What you want is not an array but a Map Commented Feb 10, 2019 at 19:39
  • @JoakimDanielson so why? I need only the array/list of strings(json objects) that is represented by a value Commented Feb 10, 2019 at 19:53
  • Because that is what your expected output looks like to me, a list of key/value pairs Commented Feb 10, 2019 at 19:56
  • @Ruslan thank you! Commented Feb 10, 2019 at 19:59

2 Answers 2

1

Sorry, this is not the correct answer for PO's question, but might be helpful for other users...who want to use GSON to (pretty) serialize object, so String jsonOutput = gson.toJson(someObject);

You "just" need to:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(jsonObject);

See here.

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

Comments

0

In your case, you only use GSON, to read (deserialize) from JSON:

JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);

For the resulting String[] and its output, your program is responsible!

...and if you don't want to re-invent the wheel, when like the "pretty" formatting & since have GSON "on board", you can do:

public static String[] toArray(String json) {
    final String PARSING_ERROR = "Error while parsing json to string array";
    // one for toJson() (only)
    final Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
    // one for fromJson (demo only)
    final Gson gsonUgly = new Gson();
    try {
        JsonObject jsonObject = gsonUgly.fromJson(json, JsonObject.class);
        String tableName = jsonObject.keySet().toArray()[0].toString();
        JsonArray jsonArray = jsonObject.getAsJsonArray(tableName);
        String[] strings = new String[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            // de-serialize & then pretty serialize each "cat".
            String catJson = jsonArray.get(i).toString();
            JsonObject catObj = gsonUgly.fromJson(catJson, JsonObject.class);
            strings[i] = gsonPretty.toJson(catObj);
        }
        return strings;
    } catch (Exception e) {
        System.err.println(PARSING_ERROR);
        throw new DataException(PARSING_ERROR);
    }
}

2 Comments

I think I should better save in db in the ugly format, and return to a client in a pretty format. Your advices were very usefull for me, thank you very much!
sounds good to me! (ugly -> db, pretty -> client) And happy to help/guide, very welcome! :-))

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.