0

This is the form data

selectedDtlId: [{"id":"3","isReviewed":true,"notes":"notes asdf test add 2"},{"id":"2","isReviewed":true,"notes":""},{"id":"1","isReviewed":true,"notes":""}]
isReviewedAll: true
notesAll: 


Upon running the below code in the Controller

Gson gson = new Gson();
gson.toJson(request.getParameter("selectedDtlId"));

response

"[{\"id\":\"3\",\"isReviewed\":true,\"notes\":\"notes asdf test add 2\"},{\"id\":\"2\",\"isReviewed\":true,\"notes\":\"\"},{\"id\":\"1\",\"isReviewed\":true,\"notes\":\"\"}]"


Expected resoponse

[
   {
      "id": "3",
      "isReviewed": true,
      "notes": "notes asdf test add 2"
   },
   {
      "id": "2",
      "isReviewed": true,
      "notes": ""
   },
   {
      "id": "1",
      "isReviewed": true,
      "notes": ""
   }
]

2 Answers 2

4

You're calling toJson when you should be calling fromJson:

gson.fromJson(request.getParameter("selectedDtlId"), JsonElement.class);

Or if you have a model:

gson.fromJson(request.getParameter("selectedDtlId"), MyModel.class);
Sign up to request clarification or add additional context in comments.

Comments

2

You should map it to a Class. (Also you are calling toJson when you should call fromJson)

Main

import com.google.gson.Gson;

public class Main {

  public static void main(String[] args) {
    String jsonInString = "[{\"id\":\"3\",\"isReviewed\":true,\"notes\":\"notes asdf test add 2\"},{\"id\":\"2\",\"isReviewed\":true,\"notes\":\"\"},{\"id\":\"1\",\"isReviewed\":true,\"notes\":\"\"}]";
    Gson gson = new Gson();

    SelectedDtlId[] selectedDtlIds = gson.fromJson(jsonInString, SelectedDtlId[].class);

    for (SelectedDtlId selectedDtlId : selectedDtlIds) {
      System.out.println("id: " + selectedDtlId.getId());
      System.out.println("notes: " + selectedDtlId.getNotes());
      System.out.println("isReviewed: " + selectedDtlId.isReviewed());
    }
  }

}

Model

import com.google.gson.annotations.SerializedName;

public class SelectedDtlId {

  @SerializedName("id")
  private int id;
  @SerializedName("isReviewed")
  private boolean isReviewed;
  @SerializedName("notes")
  private String notes;

  // getters & setters
}

the result should be:

id: 3
notes: notes asdf test add 2
isReviewed: true
id: 2
notes: 
isReviewed: true
id: 1
notes: 
isReviewed: true

1 Comment

thanks Oguzcan, for detailed explanation. Your SelectedDtlId[] selectedDtlIds = gson.fromJson(jsonInString, SelectedDtlId[].class); helped me.

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.