0

I have a requirement where i need to create the below JSON -

{ id: 1, "tags": ["Management"], name: "Amber McKenzie", title: "CEO", img: "https://cdn.balkan.app/shared/1.jpg" }

I am able to create the JSON , but got stuck in "tags": ["Management"]

I am trying the below code, but it creates like tags: "[\"External\"]"

JSONGenerator jsonGen = JSON.createGenerator(true);
string g = '["External"]';
jsonGen.writeStartArray(); 
jsonGen.writeStartObject();
jsonGen.writeStringField('tags',g); 
jsonGen.writeEndObject();
jsonGen.writeEndArray();
system.debug(jsonGen.getAsString().replace('\'',''));

How can i make it like this "tags": ["Management"]

1 Answer 1

2

I would suggest using JSON.serialize for it.

public class SomeClass {
    public void doSomethingWithRequest(String params) {
        // if you want to parse
        Wrapper wrapper = (Wrapper) JSON.deserialize(params, Wrapper.class);
        
        // if you want to generate;
        Wrapper wrapper2 = new Wrapper();
        // fill fields then
        System.debug(JSON.serializePretty(wrapper2));
        
        // or you can do like this
        Map<String, Object> someObj = new Map<String, Object> {
                'name' => 'wfwef',
                'title' => 'sdf',
                'tags' => new List<String> {
                        '1','2','3'
                }
        };

        System.debug(JSON.serializePretty(someObj));
    }
    
    public class Wrapper{
        public String name{get;set;}
        public String title{get;set;}
        public list<String> tags{get;set;}
        public String img{get;set;}
        public Integer id{get;set;}
    }
}

if you want to use JSONGenerator for it you can use writeObjectField like this

JSONGenerator jsonGen = JSON.createGenerator(true);
string g = '["External"]';
jsonGen.writeStartArray(); 
jsonGen.writeStartObject();
jsonGen.writeObjectField('tags', new List<String> {'External'}); 
jsonGen.writeEndObject();
jsonGen.writeEndArray();
system.debug(jsonGen.getAsString().replace('\'',''));
3
  • typo??JSON.stringify is a javascript method. Your code samples are correct
    – cropredy
    Commented Jun 22, 2021 at 22:23
  • 1
    you're correct I had a typo, I meant JSON.serialize) Sorry, for some reason didn't check the first line before submitting)
    – ytiq
    Commented Jun 23, 2021 at 2:31
  • fixed it, thanks. if my examples work for you, please accept the answer
    – ytiq
    Commented Jun 23, 2021 at 2:32

You must log in to answer this question.

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