一、Java使用Gson取Json字符串中Json数组里面的Json对象值
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
public class GsonTest {
public static void main(String[] args) {
String jsonString = "{\"data\":[{\"name\":\"Alice\", \"age\":25}, {\"name\":\"Bob\", \"age\":30}]}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("data");
for (JsonElement jsonElement : jsonArray) {
JsonObject dataObject = jsonElement.getAsJsonObject();
String name = dataObject.get("name").getAsString();
int age = dataObject.get("age").getAsInt();
System.out.println("Name: " + name + ", Age: " + age);
}
}
}
二、Java使用Gson将Json对象转为Json字符串
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class GsonToJsonString {
public static void main(String[] args) {
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "Alice");
jsonObject.addProperty("age", 25);
String jsonString = gson.toJson(jsonObject);
System.out.println(jsonString);
Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
String prettyJsonString = prettyGson.toJson(jsonObject);
System.out.println(prettyJsonString);
}
}