如何实现Karate特性文件到Java类的正确JSON转换
Karate测试中Java类获取正确JSON格式的解决办法
问题场景
编写的Karate测试代码如下:
* def schema = read('schema.json') * def response = read('response.json') And def jsonValidator = Java.type('feature.JsonValidator').isValid(parseSchema, response)
其中schema.json的内容为:
{ "properties": { "debtor": { "example": 1, "type": "integer" }, "creditor": { "example": 2, "type": "integer" }, "currency": { "example": 3, "type": "integer" } }, "type": "object" }
但在Java代码中收到的是Karate转换后的Java Map格式:
{properties={debtor={example=1, type=integer}, creditor={example=2, type=integer}, currency={example=3, type=integer}}, type=object}
由于Karate会自动将JSON文件解析为Java的Map/List对象,需要在Java类中获取标准JSON格式,可通过以下两种方式解决:
解决方法
方法一:在Karate侧转为JSON字符串后传入
利用Karate内置的karate.toJson()方法,将解析后的Map对象转换为标准JSON字符串,再传递给Java方法:
* def schema = read('schema.json') * def response = read('response.json') * def schemaJsonStr = karate.toJson(schema) And def jsonValidator = Java.type('feature.JsonValidator').isValid(schemaJsonStr, response)
对应的Java方法需将参数类型改为String,直接使用该字符串即可:
public class JsonValidator { public static boolean isValid(String schemaJson, Object response) { // 此处使用schemaJson进行JSON格式的验证逻辑 return true; } }
方法二:在Java侧将Map转换为JSON格式
如果无需修改Karate代码,可在Java中接收Map对象,通过JSON序列化库(如Jackson或Gson)将其转为标准JSON字符串:
使用Jackson实现:
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class JsonValidator { public static boolean isValid(Map<String, Object> schemaMap, Object response) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); String schemaJson = objectMapper.writeValueAsString(schemaMap); // 执行JSON验证逻辑 return true; } }
使用Gson实现:
import com.google.gson.Gson; import java.util.Map; public class JsonValidator { public static boolean isValid(Map<String, Object> schemaMap, Object response) { Gson gson = new Gson(); String schemaJson = gson.toJson(schemaMap); // 执行JSON验证逻辑 return true; } }
内容的提问来源于stack exchange,提问作者user22504890
相关产品推荐
相关产品推荐

