1
String selectTableSQL = "SELECT USER_ID, USERNAME from DBUSER";
Statement statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
}

With the above code..I am able to establish connection with postgres and display values from the database table. But how to parse a JSON Select query -

select array_to_json(array_agg(row_to_json(t)))
from (
  select USER_ID, USERNAME from DBUSER
) t 

The resultant json structure for the above Select query in postgres is -

[{user_id:"123",username:"abc"},{user_id:"234",username:"pqr"}]

Not understanding how to read the above json "select" query from postgres and display the values "USER_ID" and "USERNAME" separately in java.

I am just a beginner.Any Help would be appreciated.Thankyou in advance.

1
  • this tutorial might help you to parse json to java object. alternatively you can use libraries like gson or jackson for parsing the json to java. Commented Nov 17, 2016 at 16:06

2 Answers 2

3

you should use Jackson - ObjectMapper Class like this

ObjectMapper mapper = new ObjectMapper();
List<User> userList = mapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, User.class));

for(User val : userList){
    System.out.println("User id : "+val.getUserId);
    System.out.println("User id : "+val.getUserName);
}

it also work fine

List<User> userList= Arrays.asList(mapper.readValue(json, User[].class));
Sign up to request clarification or add additional context in comments.

Comments

0

let me suppose your model is like below

public class User {
 public int userId;
 public String userName; 
}

Use Gson to convert your JSON String (the return of your query) to a list of model (user in your case).

Gson gson = new Gson();
Type type = new TypeToken<List<User >>(){}.getType();
List<User> userList = gson.fromJson(jsonString, type); // where jsonString = "[{user_id:"123",username:"abc"},{user_id:"234",username:"pqr"}]" (the return of your query)
for (User user: userList ){
        System.out.println("user " + user);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.