[SalesForce] How to convert list data into json in APEX

EDIT:

I have tried something like this and I get no errors but does not display anything in the system.debug.

    String JSONString = JSON.serialize(mapWrapper);
    system.debug('JSONString : ' + JSONString );

END

Is there way to convert object list into json output?

Defined map as following:

Map<string, List<WrapperDay>>  mapWrapper = new Map<string, List<WrapperDay>>();

Output:

mapWrapper: {Monday=(WrapperDay:[index=0, record=employee:[isAllDay=false, selectedDay=Monday, selectedSection=1, selectedTo=3]]), Tuesday=(WrapperDay:[index=0, record=employee:[isAllDay=false, selectedDay=Tuesday, selectedSection=3, selectedTo=3]], WrapperDay:[index=1, record=bannerAdTimeClass:[isAllDay=false, selectedDay=Tuesday, selectedSection=4, selectedTo=3]])}

Best Answer

Fortunately Salesforce has a class to serialize and deserialize JSON. In this documentation you can find examples on how to serialize and deserialize. The examples work with single objects, but I believe you can get those in a loop and process multiple objects (like your list of custom type).

Edit:

You probably have something wrong in your code or in your logic. The following example works just fine for me:

public class Fruit {
    public Boolean isEdible;
}
public class Tree {
    public String fruit;
    public Integer age;
    public List<Fruit> fruits;
}

public String parse(){
    Tree t1 = new Tree();
    t1.fruit = 'Apple';
    t1.age = 5;

    Tree t2 = new Tree();
    t2.fruit = 'Orange';
    t2.age = 3;

    Fruit f1 = new Fruit();
    Fruit f2 = new Fruit();
    f1.isEdible = true;
    f2.isEdible = false;

    t1.fruits = new List<Fruit>{f1, f2};
    t2.fruits = new List<Fruit>{f2, f2};
    return JSON.serialize(new List<Object>{t1, t2});
}

System.debug(parse());

and it gives me:

[{"fruits":[{"isEdible":true},{"isEdible":false}],"fruit":"Apple","age":5},{"fruits":[{"isEdible":false},{"isEdible":false}],"fruit":"Orange","age":3}]

Maybe you should try to serialize a list instead of a Map object? I don't know if this can be the issue in your case.

Related Topic