
在使用springMVC的时候,我们会将返回值jsonobject转string ,这是因为springMVC最终都会转成String类型的,如果先进行转换的话,转换的逻辑就会在自己的手中。 那jsonobject如何转string呢?本文将做介绍。
第一步:控制台输入信息并接收返回的结果
1 2 3 4 5 6 7 | Scanner sc = new Scanner(System.in);
while (true)
String content = "" ;
content = sc.nextLine();
String result = TuLingApiUtil.getResult(content);
|
第二步:把json格式的字符串转化为json对象
1 | JsonObject json = new JsonParser().parse(result).getAsJsonObject();
|
第三步:获得text键的内容,并转化为string
1 | String back = json.get( "text" ).toString();
|
输出
1 | System.out.println(back);
|
需要注意的jsonobject转string后null值不输出的
例如
1 2 3 4 | JSONObject jsonObject = new JSONObject();
jsonObject.add( "name" ,null);
String str = jsonObject.toString();
str = JSONObject.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue);
|
以上就是jsonobject转string的方法,希望能对你有所帮助哦~