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.

2
  • 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). Commented Jul 24, 2014 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. Commented Jul 24, 2014 at 17:03

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.