Question

I've read some manuals for Gson, but they seem to be very difficult for me. Could you please, help me with this example? I'm complete noob here, so, please, be patient
I have the following json data:

{
"status":"Success",
"title":"No new answers",
"request":"RecentReplies",
"data":[]
} 

How can I get value of "title" line?
I've tried this one:

InputStream input = new URL("http://exampe.com/get_replies.xml").openStream();
                Reader reader = new InputStreamReader(input, "UTF-8");
                Gson gs = new Gson();
                String s = gs.fromJson(reader, String.class);

But this doesn't return anything, except come errors.

Était-ce utile?

La solution

Assuming your get_replies.xml URL really returns JSON, the simplest solution would be to define a class into which decode :

public class Thing {
    public String title;
}

And then decode as

Thing thing = gs.fromJson(reader, Thing.class);
String s = thing.title;

Autres conseils

use below code :-

Example.java

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class Example {

@Expose
private String status;
@Expose
private String title;
@Expose
private String request;
@Expose
private List<Object> data = new ArrayList<Object>();

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getRequest() {
return request;
}

public void setRequest(String request) {
this.request = request;
}

public List<Object> getData() {
return data;
}

public void setData(List<Object> data) {
this.data = data;
}

}

now

            Gson gs = new Gson();
            gs.fromJson(reader, JsonResponseClass.class);

below link for making POJO.

http://www.jsonschema2pojo.org/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top