2016-11-25 69 views
1

我的項目使用JAXB將XSD(XML模式)轉換爲POJO和cxf以將填充的類轉換爲JSON。有沒有一種工具可以接受模式,併爲我生成一個示例JSON文檔?理想的命令行或5行Java片段。什麼是從XSD XML模式(使用JAXB)生成示例JSON文檔的快速而簡單的方法?

功能方面,我想要一些類似於SoapUI爲WSDL提供的功能(即,其中包括從模式生成示例請求並使用?問號預填充所有字符串)。

我基本上想要一個快速的方法來檢查XSD模式的變化是否會產生我想要的JSON結構(所以我關心結構和類型而不是關於值)。

注意:我不想創建JSON模式,也不能使用JSON模式而不是XSD。

回答

1

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

不幸的是,這需要我來填充POJO,而不是僅僅使用缺省/隨機值...(我想優化懶惰...... ;-) – Christian

+0

@Christian所以你的問題不是將對象轉換爲json,而是如何用隨機值填充對象? –

+0

不,它是兩個。你的答案回答了我的問題約50%... ;-) – Christian

相關問題