您可以直接从使用jaxb创建的类创建json。
Jaxb创建pojo类。
任何json库都可以从pojo实例创建json。
步骤如下:
- 创建XSD
- 使用工具
xjc
- 创建类的实例创建一个从XSD的类
- 传递实例的POJO库并从中创建
String
这里以为例:
ObjectMapper mapper = new ObjectMapper();
// PojoClass is the class created with xjc from your xsd
PojoClass pojoInstance = new PojoClass();
// Populate pojoInstance as needed
String jsonString = mapper.writeValueAsString(pojoInstance);
System.out.println(jsonString); // Print the pojoInstance as json string
创建一个随机的对象可以用类似以下内容的代码来完成。请注意,此代码仅创建具有原始类型的基元类型和对象或对其他对象的引用。对于数组,列表和地图,您需要对其进行增强。
public class RandomObjectFiller {
private Random random = new Random();
public <T> T createAndFill(Class<T> clazz) throws Exception {
T instance = clazz.newInstance();
for(Field field: clazz.getDeclaredFields()) {
field.setAccessible(true);
Object value = getRandomValueForField(field);
field.set(instance, value);
}
return instance;
}
private Object getRandomValueForField(Field field) throws Exception {
Class<?> type = field.getType();
if(type.equals(Integer.TYPE) || type.equals(Integer.class)) {
return random.nextInt();
} else if(type.equals(Long.TYPE) || type.equals(Long.class)) {
return random.nextLong();
} else if(type.equals(Double.TYPE) || type.equals(Double.class)) {
return random.nextDouble();
} else if(type.equals(Float.TYPE) || type.equals(Float.class)) {
return random.nextFloat();
} else if(type.equals(String.class)) {
return UUID.randomUUID().toString();
}
return createAndFill(type);
}
}
使用这个类上面的例子是下面的代码:
ObjectMapper mapper = new ObjectMapper();
RandomObjectFiller randomObjectFiller = new RandomObjectFiller();
// PojoClass is the class created with xjc from your xsd
PojoClass pojoInstance = randomObjectFiller.createAndFill(PojoClass.class);
String jsonString = mapper.writeValueAsString(pojoInstance);
System.out.println(jsonString); // Print the pojoInstance as json string
不幸的是,这需要我来填充POJO,而不是仅仅使用缺省/随机值...(我想优化懒惰...... ;-) – Christian
@Christian所以你的问题不是将对象转换为json,而是如何用随机值填充对象? –
不,它是两个。你的答案回答了我的问题约50%... ;-) – Christian