0

I have ASP.NET webservice which return Person object in JSON format. Please see following Webservice code:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Person person() {

    Person me = new Person();
    me.name = "Mark";
    me.lastname = "Brawn";

    return me;
}


public class Person {

 public String name;
 public String lastname;
}

Then I tried to parse this response in Android client and I get following JSON Output:

{
"d": {
    "__type": "WebService+Person",
    "name": "Mark",
    "lastname": "Brawn"
}

}

This output seems valid JSON format, but I would like to know how to properly get properties from this output ( name, lastname...).

In android I parsed this output:

JSONObject json = new JSONObject(result);
json.getString("name");

But I get an exception:

07-12 19:07:14.708: W/System.err(21575): org.json.JSONException: No value for name

So actually i would like to get value "name", and "lastname" from this JSON. Any help appriciated.

rootpanthera
  • 2,731
  • 10
  • 33
  • 65

2 Answers2

1

The JSON Object being created by "result" is likely the parent JSON object, while "name" is in the nested JSON object. Try json.getObject("d").getString("name").

Jibran Khan
  • 3,236
  • 4
  • 37
  • 50
Alex Wang
  • 998
  • 1
  • 9
  • 13
  • Actually it works :). But I'm confused. Why is ASP.NET webservice returning this kind of JSON? Why not only "name" and "surname" properties? – rootpanthera Aug 19 '13 at 21:10
  • Not sure, that's a question for the developer who created the ASP.NET web service. Please accept the answer in addition to your upvote. – Alex Wang Aug 19 '13 at 21:11
  • Strange. Because I saw a lot of sample code regarding parsing JSON in android, but I never saw an output like mine ( and solution like yours ). But ok , at least it works. Thank you! – rootpanthera Aug 19 '13 at 21:13
  • FYI, the "d" is apparently a security feature in ASP.Net: http://stackoverflow.com/questions/6588589/why-do-asp-net-json-web-services-return-the-result-in-d – Emma Burrows Aug 26 '13 at 20:50
0

you can use the GSON easy to pares json data

gson download

Su Zhenpeng
  • 224
  • 1
  • 3