Usman
Usman

Reputation: 2577

How to consume/deserialize .Net WCF service JSON response in Java

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

Answers (2)

Juraj Majer
Juraj Majer

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

tom redfern
tom redfern

Reputation: 31780

I'm not sure why you're getting that response - it't not valid json. There are two things wrong with it

  1. The outer square brackets should not be wrapped in quotes.
  2. The quote escape characters need to be removed (not sure if this is just you putting them in?)

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

Related Questions