How to consume Json on Android?

Asked

Viewed 720 times

-2

How do I consume a Json on Android?

  • This is about webservice?

  • It can be http as well.

  • What do you mean "use"? Read an attribute? Create? Convert to object? If you make your question more specific, you have a better chance of getting a good answer and helping those who have the same question in the future.

  • See also : http://kobjects.org/ksoap2/index.html, can help you

1 answer

1

Hello,

Use lib Ion(REST) that provides a Jsonobject and you can make POST, GET, PUT and etc requests.

First add dependency to the app

dependencies {
    compile 'com.koushikdutta.ion:ion:2.+'
}

To read and send a json:

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

    Ion.with(context)
.load("http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});

Using callback, that is to say it will not be blocked until the answer arrives, and your return has to be treated asymptotically.

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

 JsonObject json = Ion.with(context)
.load("http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()//aqui voce define o tipo do retorno
.get();

Using the get the method has been blocked until receiving the reply and can be treated synchronously.

To treat the return in a Jsonobject:

json.get("nomeDaKey");

Link for more information from Lib:https://github.com/koush/ion

  • Do you have an example of how to work the return of json? We assume it returns id and name, how it would work in onCompleted?

  • Yes, I’ve edited the answer. I hope it helps you.

  • Hi, how do I add this library in Android Studio?

  • enters the bluild.Gradle of your project and adds this code in the dependencies "Compile 'com.koushikdutta.ion:ion:2.+ '" @Luizach

  • will yes @Luizach

  • Please, I can’t manipulate his feedback. In onCompleted, how can I get each value of json in this format [{"id":"1","name":"XXX","city":"XXXXXXX"},{"id":"2","name":"XXXX","city":"XXXXXXX"}]

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.