Reputation: 2577
I am having problem while consuming/deserializing WCF .NET JSON response in Java. JSON response is in the following format.
{"d":"[
{\"ID\":123,\"Company\":\"Microsoft\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.microsoft.com\",
\"FirstName\":\"john\",\"Email\":\"[email protected]\"},
{\"ID\":124,\"Company\":\"Google\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.google.com\",
\"FirstName\":\"john\",\"Email\":\"[email protected]\"},
{\"ID\":125,\"Company\":\"Apple\",\"Country\":\"USA\",
\"website\":\"http:\/\/www.abc.com\",
\"FirstName\":\"john\",\"Email\":\"[email protected]\"}
]"}
While on the Java code side I am having problem to deserialize this json response to get out my objects and their corresponding properties.
This is the java code currently I am using to deserialize json response.
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
if (element.isJsonObject()) {
JsonArray companies = element.getAsJsonArray();
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}
Is there any problem in the JSON response format or its right? any kind of help is appreciated, thanks in advance.
Upvotes: 0
Views: 309
Reputation: 577
Tom is right. Valid JSON should look like this:
{"d":[
{"ID":123,"Company":"Microsoft","Country":"USA",
"website":"http://www.microsoft.com",
"FirstName":"john","Email":"[email protected]"},
{"ID":124,"Company":"Google","Country":"USA",
"website":"http://www.google.com",
"FirstName":"john","Email":"[email protected]"},
{"ID":125,"Company":"Apple","Country":"USA",
"website":"http://www.aabc.com",
"FirstName":"john","Email":"[email protected]"}
]}
And your code like this:
String companyTitle = "";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonResponseString);
JsonObject object = element.getAsJsonObject();
if (object.isJsonObject()) {
JsonArray companies = object.getAsJsonArray("d");
JsonObject company = companies.get(0).getAsJsonObject();
companyTitle = company .get("Company").getAsString();
}
Upvotes: 1
Reputation: 31780
I'm not sure why you're getting that response - it't not valid json. There are two things wrong with it
Without you posting the actual error you get (hint: even though stack overflow is powerful, we have not yet developed the ability to read minds) it's very difficult to know what the actual problem is.
Upvotes: 1