1

I have a question that would like to seek your expertise on. I have Class call Technology and i retrieve data from the DB as object list of Technology classtechnologyList= getProjectBD().getAllTechnology();

my question is how to store data as key value pair in Json array. This is my code

JSONArray technologyArray=new JSONArray();
for (Technology technology : technologyList) {
        JSONArray gridRow=new JSONArray();
        gridRow.put(technology.getTechnologyId());
        gridRow.put(technology.getTechnologyName());            
        technologyArray.put(gridRow);           
    }

I need to pass this data to select option in my jsp as id and name. ex:-[1:JAVA,2:C#...]

2
  • Why not a JSONObject instead of JSONArray inside the loop? Commented Oct 21, 2015 at 9:50
  • You show the correct way sir.Thanxx Commented Oct 21, 2015 at 9:59

1 Answer 1

1

Try to use com.google.gson.* elements like that :

private JsonArray serializetechnologies(List<Technology> technologyList) {
    JsonArray jsonArray = new JsonArray();
    for (Technology technology : technologyList) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(technology.getTechnologyId()+"", technology.getTechnologyName());
        jsonArray.add(jsonObject);
    }
    return jsonArray;
}

And if you want to get value :

for (JsonElement jsonElement : jsonArray) {
    JsonObject jsonObject = (JsonObject) jsonElement;
    String name = jsonObject.get(technologyX.getTechnologyId() + "").getAsString();
    System.out.println("The name of technology witch Id = " + technologyX.getTechnologyId() + " is : "
            + name);
}

I hope that will help :)

Sign up to request clarification or add additional context in comments.

2 Comments

I need to access value using js Sir
This link expalins the concept of JS and JSP very clearly.

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.