2017-04-04 91 views
0

嗨我有一個字段在我的Json請求中它的值是一個Json。所以我將字符串轉換爲Json應用轉義字符。這個轉換後的字符串再次通過Object到Json轉換器並將其轉換爲無效的Json。字符串到Json轉換器給無效的Json值

我需要什麼:

"attributes" : {"type" : "CARES_Diagnosis_Survey__c", "referenceId" : "ref1"}, 

我在做什麼:

public static final String ATTRIBUTES_BEGIN = "{\"type\"" +":"+ "\"CARES_Diagnosis_Survey__c\""+","+"\"referenceId\"" +":"+ "\"ref"; 
public static final String ATTRIBUTES_END = "\"}"; 
String attributes = ServiceConstants.ATTRIBUTES_BEGIN + ServiceConstants.ATTRIBUTES_END; 
salesForceDiagnosisObject.setAttributes(attributes); 

This is salesForceDiagnosisObject is going through Object to Json transformer in spring integration 

<!-- turn to json --> 
    <int:object-to-json-transformer id="sfdcDiagnosisOutboundToJsonTransformer" 
     input-channel="sfdcDiagnosisObjectToJsonConverter" 
     output-channel="sfdcDiagnosisOutboundToJson" 
     /> 

什麼我得到:

"attributes":"{\"type\":\"CARES_Diagnosis_Survey__c\",\"referenceId\":\"ref\"}" 

我想什麼:

"attributes" : {"type" : "CARES_Diagnosis_Survey__c", "referenceId" : "ref1"} 

我試圖在這個字段上使用JSonIgnore來跳過序列化,但是如果我這樣做,它完全省略了字段。 請幫幫我。

回答

2

你可能做了錯誤的方式,你不映射字符串JSON,你將對象映射到JSON。

所以,如果你希望你的salesForceDiagnosisObject被序列化爲包含這樣的屬性的JSON:

{ 
    "key1" : "value1", 
    "key2" : "value2", 
.... 
    "attributes" : { 
    "type" : "CARES_Diagnosis_Survey__c", 
    "referenceId" : "ref1" 
} 

您salesForceDiagnosisObject類不能:

class SalesForceDiagnosisObject { 
    String key1; 
    String key2; 
    String attributes; 
    .... 
} 

它必須是這樣的:

class SalesForceDiagnosisObject { 
    String key1; 
    String key2; 
    DiagnosisAttribute attributes; 
    .... 
} 

和你的屬性應該像這樣設置:

當我調試
class DiagnosisAttribute{ 
    String type; 
    String referenceId; 
... 
} 

DiagnosisAttribute da = new DiagnosisAttribute(); 
da.setType("CARES_Diagnosis_Survey__c"); 
da.setReferenceId("ref1"); 

salesForceDiagnosisObject.setAttributes(da); 
+0

感謝ton @ minus。它完全解決了。是的,我做錯了。我錯誤地看到了我的要求。我一直認爲這是一個單一的領域,但事實並非如此。謝謝 – arjun

1

你的字符串看起來是正確的,它的只是反斜槓(用於轉義雙引號),使字符串看起來有點奇怪。但是,如果您生成的字符串爲sysout,則不包括斜槓。

下面是一個示例代碼,使用ObjectMapper轉換attributesMap

public static void main(String[] args) throws Exception{ 
    String ATTRIBUTES_BEGIN = "{\"type\"" +":"+ "\"CARES_Diagnosis_Survey__c\""+","+"\"referenceId\"" +":"+ "\"ref"; 
    String ATTRIBUTES_END = "\"}"; 
    String attributes = ATTRIBUTES_BEGIN + ATTRIBUTES_END; 
    ObjectMapper mapper = new ObjectMapper(); 
    Map<String, Object> value = mapper.readValue(attributes, new TypeReference<Map<String,Object>>() {}); 
    System.out.println(value); 
} 
+0

是的,我可以看到正確的字符串,不斜線之前通過對象爲JSON變壓器這是在我的Spring集成配置去。我相信它再次將這個字符串轉換成Json並給出這個不合適的Json。我試過對象映射器並使用mappervalue.toString在模型中設置。它被設置爲{type = CARES_Diagnosis_Survey__c,referenceId = ref},並且最終看起來像「attributes」:「{type = CARES_Diagnosis_Survey__c,referenceId = ref}」,所以這也是失敗的類型,它的值不有雙排隊 – arjun

+0

也謝謝你@Darshan – arjun