+ Start a Discussion
Javier CastroJavier Castro 

How to get a required JSON with List

Hi everyone,
I hope you can help me. I need to generate a JSON but the format i get it's not like I require.

I get:
"portalReformasNecesariasEdificio" : false,
"portalReformasNecesarias" : false,
"porcentajePropiedad" : 100.00,
"plazoContratoDatosOcupacionales" : null,
"plantas" : [ {
    "attributes" : {
      "type" : "HAY_Informe_Mediadores_Planta__c",
      "url" : "/services/data/v44.0/sobjects/HAY_Informe_Mediadores_Planta__c/a1G3E0000014zl0UAA"
    },
    "Id" : "a1G3E0000014zl0UAA",
    "HAY_Informe_Mediadores__c" : "a1i3E000000PvmrQAC",
    "HAY_Floor_Number__c" : 0,
    "HAY_Room_Type__c" : "01",
    "HAY_Room_Number__c" : 3
  }, {
    "attributes" : {
      "type" : "HAY_Informe_Mediadores_Planta__c",
      "url" : "/services/data/v44.0/sobjects/HAY_Informe_Mediadores_Planta__c/a1G3E0000014zl1UAA"
    },
    "Id" : "a1G3E0000014zl1UAA",
    "HAY_Informe_Mediadores__c" : "a1i3E000000PvmrQAC",
    "HAY_Floor_Number__c" : 0,
    "HAY_Room_Type__c" : "02",
    "HAY_Room_Number__c" : 1
  }],
//more fields

I need:
//fields
"plantas": [
        {
          "roomtype": "01",
          "roomnumber": "3",
          "floornumber": "0"
        },
        {
          "roomtype": "02",
          "roomnumber": "1",
          "floornumber": "0"
        },
        //etc
//more fields
I dont know how to get the result I need. I'm using a wrapper with the fields of the parent object and a list to save the child records and the JSON.SerializePretty method
class wrapper{
   //fields of the parent object {get; set;}
   List<Child__c> childs {get; set;}

   public wrapper(Parent__c parent, List<Child__c> listChilds){
     //parent fields = parent.field
     childs = listChilds
   }
}

class AnotherClass {
  //Logic to get parent data
  //Logic to get list of childs
  public method{
      String jsonBody = JSON.prettySerialize(new wrapper(parent, child),false);
  }
}

I hope you can help I'm not able to solve this.
Thanks in advance.
 
Alberto BrioschiAlberto Brioschi
Hi Javier,
Hope this can help: https://jsonformatter.curiousconcept.com/
cheers, A.
Vishal_GuptaVishal_Gupta
Hi Javier,

Please use JSONGenerator class to genrate JSON in your desired format, please check the following link :
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsongenerator.htm
https://developer.salesforce.com/index.php?title=Getting_Started_with_Apex_JSON

Let me know if you need more help. Thanks