3

Following is the valid JSON format:

String json = '{'+
        '        \"A\": \"Value of A\",'+
        '        \"B\": \"Value of B\",'+
        '        \"C\": \"Value of C\"        '+
        '}';

How should I build JSON?

If I wanted to save value of A, B and C in a variable and parse that.

String str1 = 'Value of A';
String str2 = 'Value of B';
String str3 = 'Value of C';

I tried the following:

String json = '{'+
        '        \"A\": \"'+str1+'\",'+
        '        \"B\": \"'+str2+'\",'+
        '        \"C\": \"'+str3+'\"        '+
        '}';

but this doesn't work.

Any suggestions are appreciated.

Thanks in advance.

3 Answers 3

6

You should not be escaping the double quotes inside the string, but escape only single quotes:

String jsonString = '{"A":"Some Value for A", "B", "B\'s Value"}';

Or alternatively you can build a map and then serialize it:

Map <String, String> jsonMap = new Map <String, String> ();
jsonMap.put('A', 'Some Value for A');
jsonMap.put('B', 'Some Value for B');
jsonMap.put('C', 'Some Value for C');
String jsonString = JSON.serialize(jsonMap);
1
  • 4
    This answer actually illustrates exactly why developers should be using JSON.serialize-- your first line has a typo (a comma where a colon should be). Libraries are meant to make life easier, and we should use them when we can.
    – sfdcfox
    May 20, 2015 at 23:13
3

After little more research into understanding Salesforce inbuilt JSON libraries, I ended up using JSONGenerator's

JSONGenerator generator = JSON.createGenerator(true);  
generator.writeStartObject();      
generator.writeStringField('A', 'Value of A');   
generator.writeStringField('B', 'Value of B');   
generator.writeStringField('C', 'Value of C');  

generator.writeEndObject();    

String jsonString = generator.getAsString();
system.debug('----------------------------------------------'+jsonString);

Hope this is efficient way I guess. I also like the idea of build the hasp map with objects and serializing it.

Thanks so much Bachovski for your help.

0

Have you attempted to use the static String.format() method?

It doesn't seem to like the { and } characters, but if it is just a simple JSON object you could do this:

List<String> values = new List<String>{'red','green','blue'};
String str = '"A":"{0}","B":"{1}","C":"{2}"';

String jsonString = '{' + String.format(str,values) + '}';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.