jackson:JsonNode.get().toString()获取字符串出错

本文介绍使用Jackson库处理JSON字符串时遇到的问题,当使用JsonNode的toString()方法获取字符串值时,会额外包含不必要的双引号。文章提供了解决方案,即使用asText()方法来正确获取字符串值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用jackson:JsonNode.get().toString()获取json中的字符串出错,多了一层双引号

//msg="{"method": "get_weather_city","timestamp":234655464,"req_id": 10086,"params":{"cityId":892}}"
JsonNode reqMsg = objectMapper.readTree(msg);
String method=reqMsg.get("method").toString();
//导致:method=""get_weather_city""出错
//解决方式:
//msg="{"method": "get_weather_city","timestamp":234655464,"req_id": 10086,"params":{"cityId":892}}"
JsonNode reqMsg = objectMapper.readTree(msg);
String method=reqMsg.get("method").asText();
response.setContentType("application/json"); PrintWriter out = response.getWriter(); JsonObject json = Json.createObjectBuilder().build(); try { // 创建保存目录 File saveDir = new File(SAVE_PATH); if (!saveDir.exists()) saveDir.mkdirs(); // 获取表单数据 String username = request.getParameter("username"); String password = request.getParameter("password"); String sex = request.getParameter("sex"); String realname = request.getParameter("realname"); String email = request.getParameter("email"); String telephone = request.getParameter("telephone"); String idNum = request.getParameter("idNum"); int phone = Integer.parseInt(telephone); int id = Integer.parseInt(idNum); // 处理头像上传 Part filePart = request.getPart("headimg"); String fileName = getFileName(filePart); String filePath = ""; if (fileName != null && !fileName.isEmpty()) { // 生成唯一文件名 String ext = fileName.substring(fileName.lastIndexOf(".")); String uniqueName = UUID.randomUUID() + ext; filePath = SAVE_PATH + File.separator + uniqueName; // 保存文件 try (InputStream fileContent = (InputStream) filePart.getInputStream()) { Files.copy(fileContent, Paths.get(filePath)); } } // 创建用户对象 User user = new User(username,password,sex,realname,email,phone,id,filePath); // 保存到数据库(需实现UserService) UserService userService = new UserServiceImpl(); int result = userService.addUser(user); if (result > 0) { json = Json.createObjectBuilder() .add("code", 200) .add("msg", "用户添加成功") .build(); } else { json = Json.createObjectBuilder() .add("code", 500) .add("msg", "数据库操作失败") .build(); } } catch (Exception e) { json = Json.createObjectBuilder() .add("code", 500) .add("msg", "服务器错误: " + e.getMessage()) .build(); } out.print(json.toString()); out.flush(); } // 获取上传文件名 private String getFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); String[] tokens = contentDisp.split(";"); for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length() - 1); } } return ""; }可以更换JsonObject json = Json.createObjectBuilder().build();这个方法吗
06-16
package com.luxsan.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.seg.common.Term; import com.luxsan.common.core.exception.ServiceException; import com.luxsan.common.core.exception.file.FileException; import com.luxsan.common.core.utils.MessageUtils; import com.luxsan.domain.ValidationResult; import lombok.RequiredArgsConstructor; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @RequiredArgsConstructor @Service public class PdfJsonCompareService { private final Map<String, Pattern> patternCache = new ConcurrentHashMap<>(); private final ObjectMapper objectMapper = new ObjectMapper(); public String readPdfText(MultipartFile file) { try (PDDocument doc = PDDocument.load(file.getInputStream())) { PDFTextStripper stripper = new PDFTextStripper(); String rawText = stripper.getText(doc); return rawText.replaceAll("\\s+", " ").trim(); // 统一空白符 } catch (Exception e) { return MessageUtils.message("file.red.pdf.error"); } } public JsonNode parseJson(String jsonContent) throws Exception { return this.objectMapper.readTree(jsonContent); } public List<ValidationResult> compareContent(String pdfText, JsonNode jsonConfig) { List<ValidationResult> results = new ArrayList<>(); //处理 JSON 结构(支持单个对象或数组) JsonNode dataNode; if (jsonConfig.isArray() && jsonConfig.size() > 0) { dataNode = jsonConfig.get(0); } else if (jsonConfig.isObject()) { dataNode = jsonConfig; } else { results.add(new ValidationResult("ERROR", "JSON格式错误", "期望一个对象或包含对象的数组", "实际格式不匹配", false)); return results; } // 定义地址字段列表 Set<String> addressFields = new HashSet<>(Arrays.asList("SHIPTOCITY", "SHIPTOSTATE", "SHIPTOZIP", "SOLDTOCITY", "SOLDTOSTATE", "SOLDTOZIP")); //字段直接匹配 checkNonAddressFields(pdfText, dataNode, results, addressFields); //连续匹配 checkAddressFields(pdfText, dataNode, results, addressFields); return results; } /** * 检查 JSON 中非地址字段是否严格存在于 PDF 文本中 */ private void checkNonAddressFields(String pdfText, JsonNode jsonConfig, List<ValidationResult> results, Set<String> addressFields) { Iterator<Map.Entry<String, JsonNode>> fields = jsonConfig.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String fieldName = entry.getKey(); JsonNode valueNode = entry.getValue(); if (valueNode.isValueNode() && !addressFields.contains(fieldName)) { String expectedValue = valueNode.asText().trim(); if (expectedValue.isEmpty()) continue; // 使用正则表达式进行严格匹配 String regex = "\\b" + Pattern.quote(expectedValue) + "\\b"; Pattern pattern = getCachedPattern(regex); Matcher matcher = pattern.matcher(pdfText); boolean found = matcher.find(); results.add(new ValidationResult( "FIELD", fieldName, expectedValue, found ? "Found" : "Not Found", found )); } } } /** * 获取或创建缓存中的 Pattern 对象 */ private Pattern getCachedPattern(String regex) { return patternCache.computeIfAbsent(regex, Pattern::compile); } /** * 检查 JSON 中地址字段是否严格存在于 PDF 文本中 */ private void checkAddressFields(String pdfText, JsonNode jsonConfig, List<ValidationResult> results, Set<String> addressFields) { List<Term> terms = HanLP.segment(pdfText); List<String> addressParts = new ArrayList<>(); for (Term term : terms) { String word = term.word; if (word.matches("\\d{5,7}")) { addressParts.add(word); } else if (term.nature.toString().startsWith("ns")) { addressParts.add(word); } } // 遍历 JSON 配置中的地址字段 Iterator<Map.Entry<String, JsonNode>> fields = jsonConfig.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String fieldName = entry.getKey(); JsonNode valueNode = entry.getValue(); if (valueNode.isValueNode() && addressFields.contains(fieldName)) { String expectedValue = valueNode.asText().trim(); if (expectedValue.isEmpty()) continue; boolean found = false; for (String part : addressParts) { if (part.equals(expectedValue)) { found = true; break; } } results.add(new ValidationResult( "FIELD", fieldName, expectedValue, found ? "Found" : "Not Found", found )); } } } } package com.luxsan.controller; import com.fasterxml.jackson.databind.JsonNode; import com.luxsan.common.core.domain.R; import com.luxsan.common.core.utils.MessageUtils; import com.luxsan.domain.ValidationResult ; import com.luxsan.service.PdfJsonCompareService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/pdfJson") @RequiredArgsConstructor public class PdfJsonCompareController { private final PdfJsonCompareService compareService; /** * 上传PDF文件和JSON内容,返回对比结果 */ @PostMapping("/compare") public R compare(@RequestParam("pdfFile") MultipartFile pdfFile, @RequestParam("jsonContent") String jsonContent){ //读取PDF文本 String pdfText = compareService.readPdfText(pdfFile); // 2. 解析JSON配置 JsonNode jsonConfig = null; try { jsonConfig = compareService.parseJson(jsonContent); } catch (Exception e) { R.fail("file.red.pdf.error"); } // 3. 执行对比校验 List<ValidationResult> results = compareService.compareContent(pdfText, jsonConfig); //返回没有匹配成功的数据 List<ValidationResult> failedResults = new ArrayList<>(); for (ValidationResult result : results) { if (!result.isValid()) { failedResults.add(result); } } if (failedResults.isEmpty()) { return R.ok("条件符合"); } else { return R.ok(failedResults); } } } 这哪里需要优化一下
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值