您可以直接從使用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