我想修补一个JSON字符串。我得到了必须修补的字段的"路径",以及要修补的"值"。 该值可以是任何内容,字符串、整数、浮点数、布尔值、数组或对象。
如何将对象转换为 JsonValue?
javax.json.JsonPointer 类中的"replace"方法需要一个 JsonValue 对象。
使用这个
import com.google.gson.Gson;
Statue statue = new Statue();//java class
String json = new Gson().toJson(statue);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Json 将采用 java 类结构
您可以使用Jackson,它可以与Maven一起添加到 pom 中,指定以下依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
使用Jackosn,您可以使用ObjectMapper(使用import com.fasterxml.jackson.databind.ObjectMapper;
导入(。因此,如果您有一个 MyClass 类型的对象obj
,您可以执行以下操作:
MyClass objToCovert = new MyClass();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);
必须将 json 传递给将 Json 结构更新为修补程序的方法。作为可以进行更新的方法的示例,我报告以下内容(tag
是关键(:
public static JsonStructure updateKeyValue(JsonStructure jsonStructure, String tag, String value) {
JsonPointer jsonPointer = Json.createPointer("/" + tag);
JsonString jsonStringValue = (JsonString) jsonPointer.getValue(jsonStructure);
jsonStructure = jsonPointer.replace(jsonStructure, jsonStringValue);
return jsonStructure;
}