0

I get a json string in server side as follow

[     {"projectFileId":"8547",
       "projectId":"8235",
       "fileName":"1",
       "application":"Excel",
       "complexity":"NORMAL",
       "pageCount":"2",
       "targetLanguages":" ar-SA",
       "Id":"8547"
      },
      {"projectFileId":"8450",
       "projectId":"8235",
       "fileName":"Capacity Calculator.pptx",
       "application":"Powerpoint",
       "complexity":"NORMAL",
       "pageCount":"100",
       "targetLanguages":" ar-LB, ar-SA",
       "Id":"8450"
      }
]

I want to convert this string into an arraylist or map whichever possible so that I can iterate over it and get the field values.

Jorge Campos
  • 22,647
  • 7
  • 56
  • 87
Mayur Sawant
  • 39
  • 1
  • 2
  • 5
  • 1
    Use a JSON parser. There are about 20 to choose from, listed on the bottom of the page json.org (which is a good page to visit anyway, to learn the JSON syntax). – Hot Licks Jul 24 '14 at 17:01
  • And that data is a JSON array containing two JSON objects. This is equivalent to a Java List containing two Java Maps. – Hot Licks Jul 24 '14 at 17:03

1 Answers1

2

You can use GSON library. Simply use Gson#fromJson() method to convert JSON string into Java Object.

sample code:

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = gson.fromJson(reader, type);

// convert back to JSON string from object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

You can create a POJO class to convert it directly into List of POJO clas object to access it easily.

sample code:

class PojectDetail{
    private String projectFileId;
    private String projectId;
    private String fileName;
    private String application;
    private String complexity;
    private String pageCount;
    private String targetLanguages;
    private String Id;
    // getter & setter
}

Gson gson = new Gson();
Type type = new TypeToken<ArrayList<PojectDetail>>() {}.getType();
ArrayList<PojectDetail> data = gson.fromJson(reader, type);
Braj
  • 46,415
  • 5
  • 60
  • 76