0

I am using the JSON Generator class to create the JSON. but in response backslash get added.

Result:

"{\"Id\":\"a171j000000WDQCAA4\",\"Name\":\"Q-00123\"}"

Could you please suggest me how we generate the Json with out backslash.

Method:

public static string responseCall(Id QId){ 
    List<SBQQ__Quote__c> q=[select Id , Name from SBQQ__Quote__c where Id=:QId];   
    JSONGenerator gen = JSON.createGenerator(false);
    
    for(SBQQ__Quote__c quoteDtls : q){      
        gen.writeStartObject();
        gen.writeStringField('Id', quoteDtls.Id);
        gen.writeStringField('Name', quoteDtls.Name);
        gen.writeEndObject();
    }

    system.debug(gen.getAsString());

    return gen.getAsString();           
}

Thanks in advance

2
  • Please add code or metadata to reproduce the problem.
    – identigral
    Commented Jul 15, 2020 at 9:28
  • public static string responseCall(Id QId){ List<SBQQ__Quote__c> q=[select Id , Name from SBQQ__Quote__c where Id=:QId]; JSONGenerator gen = JSON.createGenerator(false); for(SBQQ__Quote__c quoteDtls : q){ gen.writeStartObject(); gen.writeStringField('Id', quoteDtls.Id); gen.writeStringField('Name', quoteDtls.Name); gen.writeEndObject(); } system.debug(gen.getAsString()); return gen.getAsString(); } Commented Jul 15, 2020 at 9:39

1 Answer 1

0

This code is not responsible for the backslashes. I tested this in my developer org. Note that, however, it also won't generate valid JSON, as you need to wrap the entire thing in an array (writeStartArray and writeEndArray).

JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartArray();
for(SBQQ__Quote__c quoteDtls : q){      
    gen.writeStartObject();
    gen.writeStringField('Id', quoteDtls.Id);
    gen.writeStringField('Name', quoteDtls.Name);
    gen.writeEndObject();
}
gen.writeEndArray();
system.debug(gen.getAsString());
return gen.getAsString();           

You'll need to look elsewhere in your code to figure out where the escapes (the \ characters) are coming from.

2
  • can you call this code using postman. I mean create the post method and return should be string see what exactly return Commented Jul 15, 2020 at 13:22
  • @user3652558 Yes, your post method may be the problem, depending on a variety of factors. That is what I attempted to convey in my answer. This code is just fine, it's your main method that's encoding the JSON string a second time.
    – sfdcfox
    Commented Jul 15, 2020 at 13:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .