第一种
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String json="{\"translation\":\"你好吗\"}";
//String json="{'translation':'你好吗'}";
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();

String fieldValue = jsonObject.get("translation").getAsString();

System.out.println(fieldValue); //你好吗
第二种
// 假设你已经有一个名为 responseEntity 的 ResponseEntity<String> 对象
ResponseEntity<String> responseEntity = ...

// 获取响应体的字符串内容
String responseBody = responseEntity.getBody();

// 将字符串转换成相应的数据类型,假设这里是 JSON 字符串
// 使用合适的 JSON 解析库将字符串转换成 JSON 对象
// 假设你使用的是 Jackson
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);

// 根据 JSON 的结构,访问对象的属性获取具体参数
String param1 = jsonNode.get("param1").asText();
int param2 = jsonNode.get("param2").asInt();
boolean param3 = jsonNode.get("param3").asBoolean();
 第三种对象赋值
//要将返回的结果赋值给BaseResp对象,您需要先将返回结果转换为BaseResp对象的类型。假设BaseResp是一个自定义的类,您需要按照BaseResp的字段结构,手动解析返回的结果并赋值给BaseResp对象的相应字段

ResponseEntity<String> response = restTemplate.postForEntity(targetUrl, requestEntity, String.class);
String result = response.getBody();

// 创建一个ObjectMapper对象,用于进行JSON解析
ObjectMapper objectMapper = new ObjectMapper();

// 将返回结果解析为BaseResp对象
BaseResp baseResp = objectMapper.readValue(result, BaseResp.class);


//这里假设BaseResp类已经正确定义,并且其字段与返回结果中的字段名相匹配。如果字段名不匹配,您可能需要通过注解或配置来进行字段映射。另外,您需要导入相应的Jackson库依赖。
 第四种
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject; 
 @Test
  void contextLoadss() throws IOException, NoSuchAlgorithmException {

      String yw ="{\"errorCode\":\"0\",\"msg\":null,\"result\":[{\"sentence\":\"Can I purchase duty free items before my flight?\",\"vad_id\":1,\"partial\":false}]}";
      JSONObject jsonObject = new JSONObject(yw);
      JSONArray resultArray = jsonObject.getJSONArray("result");
      JSONObject resultObject = resultArray.getJSONObject(0);
      String sentence = resultObject.getStr("sentence");
      System.out.println(sentence);
  }

 

posted on 2023-08-22 10:45  鲤斌  阅读(1338)  评论(0编辑  收藏  举报