[SalesForce] Serialize list of objects to json array not working as expected

It seems like in some instances apex is serializing Lists differently. I need it to serialize a list to a json array, however I'm getting a comma separated list of objects.

Why does this give me a csv string of objects that looks like this ?({property=name, value=mike}, {property=age, value=47})

Map<String, Object> m = new Map<String, Object>();
m.put('property', 'name');
m.put('value', 'mike');

Map<String, Object> m2 = new Map<String, Object>();
m2.put('property', 'age');
m2.put('value', 47);

List<Object> x = new List<Map<String, Object>>();
x.add(m);
x.add(m2);

string y = JSON.serialize(x);

System.debug(x);

Whereas this gives me an array of strings that looks like this? ["January","February","March","April","May","June","July","August","September","October","November","December"]

List<String> months = new List<String>{'January','February','March','April','May','June','July','August','September','October','November','December'};
string a = JSON.serialize(months);
System.debug(a);

Best Answer

You are serializing variable x into variable y ,and still priting variable x which is unchanged.

fix: Print variable y

Map<String, Object> m = new Map<String, Object>();
m.put('property', 'name');
m.put('value', 'mike');

Map<String, Object> m2 = new Map<String, Object>();
m2.put('property', 'age');
m2.put('value', 47);

List<Object> x = new List<Map<String, Object>>();
x.add(m);
x.add(m2);

string y = JSON.serialize(x);

System.debug(y);