2017-04-04 24 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