Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package dummy.json;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;
public class GsonSample {
public static void main(String... args) {
String json = "{'k1':'apple','k2':123, 'k3':123.0, 'k4':123}";
// test0(json);
test1(json);
}
public static void test0(String json) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> myMap = gson.fromJson(json, type);
System.out.println(myMap);
myMap.forEach(
(String key, Object val) -> {
System.out.println("key:" + key);
});
// Double cannot cast to Long.
// Long val2 = (Long) myMap.get("k2");
Double d1 = Double.valueOf(12.345);
Double d2 = Double.valueOf(12.345);
Double d3 = Double.valueOf(12.3456);
System.out.println("d1 == d2: " + d1.equals(d2));
System.out.println("d1 == d3: " + d1.equals(d3));
Double d4 = Double.valueOf(12.0);
Double d5 = Double.valueOf(12);
System.out.println("d4 == d5: " + d4.equals(d5));
// JsonObject elem = gson.fromJson("{'k1':'apple','k2':123}", JsonObject.class);
// elem.getAsJsonObject()
// .entrySet()
// .forEach((kv) -> System.out.println(kv.getKey() + kv.getValue().));
}
public static void test1(String json) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonElement root = parser.parse(json);
root.getAsJsonObject()
.entrySet()
.forEach(
entry -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
System.out.println("isJsonPrimitive(): " + entry.getValue().isJsonPrimitive());
System.out.println("isNumber(): " + entry.getValue().getAsJsonPrimitive().isNumber());
});
Number k2 = null;
Number k3 = null;
Number k4 = null;
for (Map.Entry<String, JsonElement> ent : root.getAsJsonObject().entrySet()) {
if (ent.getKey().equals("k2")) k2 = ent.getValue().getAsNumber();
if (ent.getKey().equals("k3")) k3 = ent.getValue().getAsNumber();
if (ent.getKey().equals("k4")) k4 = ent.getValue().getAsNumber();
}
Objects.requireNonNull(k2, "k2 is null");
Objects.requireNonNull(k3, "k3 is null");
Objects.requireNonNull(k4, "k4 is null");
System.out.println("k2 == K3: " + (k2 == k3)); // false
System.out.println("k2 == K4: " + (k2 == k4)); // false
System.out.println("k2.equals(k3): " + k2.equals(k3)); // false
System.out.println("k2.equals(k4): " + k2.equals(k4)); // true
// Numberは整数と浮動小数点は == もequalsも等しくならないが、
// 数値型が同じで数値が同じ場合はequalsメソッドはtrueを返す。
// でもインスタンスは異なるので == はfalseを返す。
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment