下面是我的代码,我试图在 json 中设置值
我有 JSON
{
"Details": "{\"user\":\"user1\",\"password\":\"1234\"}"
}
这里我必须在 user 和 pass 中设置数据,但它是双引号的
我尝试了 with-detail.user 路径,但它不起作用。
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = (ObjectNode) mapper.readTree(new File(templatePath)); // // System.out.println(node); Configuration config = Configuration.builder() .jsonProvider(new JacksonJsonNodeJsonProvider()) .mappingProvider(new JacksonMappingProvider()).build(); json = JsonPath.using(config).parse(node);
for (int i = 0; i < list.size(); i++) {
String x = list.get(i);
arr = x.split(": ");
String newHeader = arr[0].replace("|", ".");
if (newHeader.contains("[")) {
String nHeader = "$." + newHeader;
String actualVal;
if (arr.length >= 2) {
actualVal = arr[1];
} else {
actualVal = "";
}
json.set(nHeader, actualVal).jsonString();
}
else{
String actualVal;
if (arr.length >= 2) {
actualVal = arr[1];
} else {
actualVal = "";
}
json.set(newHeader, actualVal).jsonString();
}
我已经尝试了上面的代码来设置数据。但我遇到了例外。
参考以下代码并尝试更新您的对象。您可以使用 gson 或 jackson 来处理 JSON 对象。在发布问题之前请先做一些工作。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUpdateExample {
public static void main(String[] args) {
// Sample JSON string
String jsonString = "{\"name\":\"John\", \"age\":25, \"city\":\"New York\"}";
// Field to update
String fieldToUpdate = "age";
// New value for the field
int newValue = 30;
// Update the JSON
String updatedJson = updateJsonField(jsonString, fieldToUpdate, newValue);
// Print the updated JSON
System.out.println(updatedJson);
}
private static String updateJsonField(String jsonString, String fieldToUpdate, int newValue) {
try {
// Create ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
// Read the JSON string into a JsonNode
JsonNode jsonNode = objectMapper.readTree(jsonString);
// Update the field
((ObjectNode) jsonNode).put(fieldToUpdate, newValue);
// Convert the updated JsonNode back to a JSON string
return objectMapper.writeValueAsString(jsonNode);
} catch (Exception e) {
e.printStackTrace();
return jsonString; // return the original JSON in case of an error
}
}
}