2015-05-27 150 views
0

我是Spring MVC和JSON的noob。我有一個類層次結構(接口,類,子類),我想發送到我的視圖,然後復活視圖中的對象(也許一些Json庫,目前使用FlexJson)。Spring MVC發送所有模型類作爲json字符串

這個想法背後是我試圖根據我的配置層次結構中的類生成工具箱,允許用戶通過拖放(使用jQuery?)項目(配置層次結構中的類型)來創建系統,在每個項目上設置各種屬性(屬性),並最終保存並將配置發送回持久化。

那麼遠,我只得到儘可能使用Reflections Library作爲這樣的收穫包(子)類型(的對象):

Reflections reflections = new Reflections(new ConfigurationBuilder() 
      .setUrls(ClasspathHelper.forPackage("com.obsm.myapp.model.configuration")) 
      .setScanners(new SubTypesScanner(false)) 
      .filterInputsBy(new FilterBuilder().includePackage("com.obsm.myapp.model.configuration"))); 
    Set<Class<?>> types = reflections.getSubTypesOf(Object.class); 

任何幫助深表感謝。

回答

0

經過相當多的谷歌搜索和嘗試失敗後,我已經解決了以下問題。我有一個Util類,如果我通過Class,則會得到一個json字符串。我現在使用Jackson Library來獲取json表示。

public class Util { 

public static String toJsonString(Class<?> entity) 
{ 
    ObjectMapper mapper = new ObjectMapper(); 
    String json = ""; 
    try { 
     String toolItemMode = ""; 
     List<Class<?>> interfaceList = Arrays.asList(entity.getInterfaces()); 
     if (interfaceList.contains(IConnectableObject.class)) 
     { 
      toolItemMode = "both"; 
     } 
     else if (interfaceList.contains(IConnectionSource.class)) 
     { 
      toolItemMode = "source"; 
     } 
     else if (interfaceList.contains(IConnectionSink.class)) 
     { 
      toolItemMode = "sink"; 
     } 

     json = mapper.writeValueAsString(entity.newInstance()); 
     ObjectNode objectNode = (ObjectNode) mapper.readTree(json); 
     objectNode.put("mode", toolItemMode); 
     json = objectNode.toString(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (InstantiationException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } 
    return json; 
} 
} 

然後在控制器方法我做這種方式...

..... 
Reflections reflections = new Reflections("com.obsm.myapp.model.configuration"); 
    Set<Class<? extends IConfigurationEntity>> classes = reflections.getSubTypesOf(IConfigurationEntity.class); 
    Map<String, String> toolBox = new HashMap<String, String>(); 
    for (Class<? extends IConfigurationEntity> configItem : classes) 
    { 
     toolBox.put(configItem.getSimpleName(), Util.toJsonString(configItem)); 
    } 
model.addAttribute("toolBox", toolBox); 
..... 

如果有人有什麼更好的主意,我敢肯定,你們許多人,我渴望瞭解它們。希望這可以幫助別人。 :-)

相關問題