[SalesForce] Json serialize not giving me correct format

My end result needs to be something like this:

    [{
      "label": "Sales",
      "color": "#9cd159",
      "data": [
        ["Jan", 27],
        ["Feb", 82],
        ["Mar", 56],
        ["Oct", 20]
      ]
    }]

my apex is as follows:

    class Report {   
        public String label;        
        public String color;
        public Data[] data;
    }
    class Data{
        public String key;
        public Integer value;
    }

my json serialize class is this:

    public String ReportOne{

            Report myReport = new Report();
            myReport.label = 'Sales';
            myReport.color = '#9cd159';

            myReport.data = new Data[]{};

            Data d1 = new Data();
            d1.key = 'Mon';
            d1.value = 13;

            myReport.data.add(d1);

            return JSON.serialize(myReport);
     }

The end result is being like this:
What am I doing wrong?

{
  "color": "#9cd159",
  "data": [
    {
      "key": "Mon",
      "value": 13
    }
  ],
  "label": "Sales"
}

Best Answer

Using JSON2Apex very useful site to bookmark you get the following output from your listed request of:

[{
      "label": "Sales",
      "color": "#9cd159",
      "data": [
        ["Jan", 27],
        ["Feb", 82],
        ["Mar", 56],
        ["Oct", 20]
      ]
    }]

Yields

// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class JSON2Apex {

    public String label;
    public String color;
    public List<List<String>> data;


    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}

Depending on what you are trying to do and based on your question you may mean this:

{"reports":[{
      "label": "Sales",
      "color": "#9cd159",
      "data": [
        ["Jan", 27],
        ["Feb", 82],
        ["Mar", 56],
        ["Oct", 20]
      ]
    }]
}

Which yields this:

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class JSON2Apex {

    public List<Reports> reports;

    public class Reports {
        public String label;
        public String color;
        public List<List<String>> data;
    }


    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
}

The problem is like I said, your question is an Unnamed array [] and to be valid JSON yet still return the [] you need to name it and then you can access the array by using xxx.reports

Related Topic