[SalesForce] Add a new key-value to a json string

The scenario is as follow, I got a json which was converted to a string, I need to add to that json another key-value pair.

I assume it requires to convert the string back to json, how would that work?

Class_A:

List<String> jsonStrings;
JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
gen.writeStringField('_id', '1234');
gen.writeStringField('title', '2345');
gen.writeEndObject();
jsonStrings.add(gen.getAsString());
Class_B classBinstance = new Class_B(jsonStrings[0]);

Class_B:

public Class B(String json){
    JSONGenerator gen = JSON.createGenerator(false);
    //TODO: get the json string from Class A, convert it back to json and add to it another key-value pair
}

Best Answer

Instead you can pass json generator object directly to class b.

public class Class_B{
    JSONGenerator gen;
    Class_B(JSONGenerator gen){
        this.gen = gen;
    }
}

List<String> jsonStrings;
JSONGenerator gen = JSON.createGenerator(false);
gen.writeStartObject();
gen.writeStringField('_id', '1234');
gen.writeStringField('title', '2345');
gen.writeEndObject();

Class_B classBinstance = new Class_B(gen);
Related Topic