1

I hava a javascript object that im passing back to java via ajax:

var jsonData = {   
        "testJson" : "abc",  
        "userId" : "123" 
}; 

When I println the map it looks like:

key: jsondata value:[object Object]

How can I properly parse the object?

4
  • Read about parsing json objects Commented Feb 28, 2016 at 19:45
  • do not include anything but the object to the string you pass to java. { ... } Commented Feb 28, 2016 at 19:52
  • 1
    Is this a javascript or java question? In javascript the posted code defines an object called jsonData. This would need to be converted into a string ( using JSON.stringify ) before passing back to the server. Commented Feb 28, 2016 at 20:54
  • @Traktor53. That was my problem...I didnt turn the object to json before sending it back....thanks Commented Feb 28, 2016 at 21:15

3 Answers 3

1

You can use GSON in java:

class MyObject() {
  String testJson;
  String userId;

  public void setTestJson(String testJson) {
    this.testJson=testJson;
  }
  public String getTestJson() {
    return testJson;
  }
  ... Same for userId
}

And then create a GSON object:

class SomeClass {
  public void parseMyJson(String json) {
    Gson gson=new Gson();
    MyObject mo=gson.fromJson(json,MyObject.class);
  }
}

In which mo now contains you json object with just the use of getters and setters

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

Comments

0

I hope, this can help you: int userId = object.getInt("userId");

https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

Comments

0

As posted the code defines a javascript object called jsonData. This can be converted into a string ( using JSON.stringify ) before passing back to the server:

var jsonData = {   
    "testJson" : "abc",  
    "userId" : "123" 
};
var jsonString = JSON.stringify( jasonData);

or alternatively in trivial cases by defining the JSON string directly:

var jsonString = `{"testJson" : "abc",  "userId" : "123" }';

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.