Jason Fung
Jason Fung

Reputation: 69

How to create JSON response with nested array

I have a list which looks like this:

{
  "data1": "abcd",
  "data2": "efgh",
}

I'm trying to create a JSON response in this format by looping the above array and building the below:

{
  "id": "123456",
  "nestedArray": [
    {
      "data1": "abcd",
      "somedata": 1234
    },
    {
      "data2": "efgh",
      "somedata": 1234
    }
  ]
}

I've created a model to map the structure of the nested array:

public class nestedArray{
    public String data1;
    public Integer data2;

    public nestedArray(string data) {
        this.data1 = uri;
        this.data2 = 1234;
    }
}

But i'm stuck on how to build the final response, any pointers is much appreciated!

Upvotes: 0

Views: 462

Answers (1)

Akshay Jain
Akshay Jain

Reputation: 11

Try this :

JSON:

{
  "id": "123456",
  "nestedArray": [
    {
      "data1": "abcd",
      "somedata": 1234
    },
    {
      "data1": "efgh",
      "somedata": 1234
    }
  ]
}

Model:
public class Resp {

    public class NestedArray {
        public String data1;
        public Integer somedata;
    }

    public String id;
    public List<NestedArray> nestedArray;


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

Upvotes: 1

Related Questions