Wermescher Advisory Logo

Google Gson in a nutshell

Inhaltsverzeichnis

JsonObject vs JsonArray

Create a JsonObject

JsonObject jo = new JsonObject();
jo.addProperty("url", url);
jo.addProperty("type", "source");
ja.add(jo);

Create a JsonArray

JsonArray ja= new JsonArray();
JsonObject jo1 = new JsonObject();
jo1.addProperty("key", "key1");
jo1.addProperty("value", "value1");
ja.add(jo1);
JsonObject jo2 = new JsonObject();
jo2.addProperty("key", "key2");
jo2.addProperty("value", "value2");
ja.add(jo2);

Iterate / Loop through all JsonObjects inside a JsonObject

Map<String, Object> attributes = new HashMap<String, Object>();
Set<Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
   System.out.println("Key: " + entry.getKey());
   JsonObject item = jsonObject.get(entry.getKey()).getAsJsonObject(); 
}

Parse String into JsonObject

String json = "{ \"name\": \"Herwart\", \"value\": true }";
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();

Add a list of strings

public static void Add(JsonObject jo, String property, List<String> values) {
        JsonArray array = new JsonArray();
        for (String value : values) {
            array.add(new JsonPrimitive(value));
        }
        jo.add(property, array);
    }

Parse from json file

FileReader fr = new FileReader(filename);
Object obj = JsonParser.parseReader(fr).getAsJsonObject();

Get info from object

String start = jo.get("start").getAsString();

Print out json

Compact print

String[] lang = {"Java", "PHP"};
Gson gson = new Gson();
String json = gson.toJson(lang);

Pretty print

String[] lang = {"Java", "PHP"};

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(lang);

System.out.println(json);

Teilen:

Weitere Posts

WordPress Website 3: Welche Plugins

Page Builder Elementor (und Elementor Pro) SEO RankMath Statistik Matomo Newsletter MailPoet Security und Firewall Wordfence Wordfence ist eine umfassende Security Lösung für WordPress und

Sende uns eine Nachricht