Doc Holiday
Doc Holiday

Reputation: 10254

Java parse Object

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?

Upvotes: 1

Views: 1083

Answers (3)

traktor
traktor

Reputation: 19301

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" }';

Upvotes: 0

Samuel P
Samuel P

Reputation: 33

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

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

Upvotes: 0

Norbert
Norbert

Reputation: 6084

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

Upvotes: 1

Related Questions