1.使用ObjectMapper
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{"name": "Alice", "age": 30, "city": "New York"}";
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
String city = jsonNode.get("city").asText();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.使用Gson
import com.google.gson.Gson
import com.google.gson.JsonObject
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{"name": "Alice", "age": 30, "city": "New York"}"
Gson gson = new Gson()
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class)
String name = jsonObject.get("name").getAsString()
int age = jsonObject.get("age").getAsInt()
String city = jsonObject.get("city").getAsString()
System.out.println("Name: " + name)
System.out.println("Age: " + age)
System.out.println("City: " + city)
}
}
3.使用fastjson
import com.alibaba.fastjson.JSONObject
public class JsonExample {
public static void main(String[] args) {
String jsonString = "{"name": "Alice", "age": 30, "city": "New York"}"
JSONObject jsonObject = JSONObject.parseObject(jsonString)
String name = jsonObject.getString("name")
int age = jsonObject.getInteger("age")
String city = jsonObject.getString("city")
System.out.println("Name: " + name)
System.out.println("Age: " + age)
System.out.println("City: " + city)
}
}