简体   繁体   中英

how to convert the values from a json array to a java string

I need to take the values from a JSON array and display them. Below is the code I have used.

getresponse class will send a HTTP request to a PHP page and get the relevant JSON array and the public variable res will hold that returned JSON array.

public class JSONConverter {
     public void convert(){
        getresponse gr=new getresponse();
        String json = gr.res;
        Data data = new Gson().fromJson(json, Data.class);
        System.out.println(data);
    }
}

class Data {
    private String city;
    private int reserve_no;

    public String getCity() { return city; }
    public int getReserve_no() { return reserve_no; }

    public void setTitle(String city) { this.city = city; }
    public void setId(int reserve_no) { this.reserve_no = reserve_no; }

    public String toString() {
        return String.format(city);
    } 
}

getrespose class

public class getresponse {
public static String res;
  public void counter() {
 try {
    URL url = new URL("http://taxi.net/fetchLatest.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));
            String str;
    while ((str =br.readLine()) != null) {                                  
                    res=str;

    }

    conn.disconnect();

Below is an example of JSON array returned.

[{"reserve_no":"20","city":"city2","street":"street1234","discription":"discription123","date":"2012-10-22 04:47:54","customer":"abc"}]

This code doesn't display the city name of the JSON array returned. can someone help me with this by correcting the code or suggest a better or easier method if any? :)

Gson maps json string to your class basing on your class properties names. So Data class has property title which is supposed to be mapped to city in json array. You need to rename you property to city so Gson can figure out where to put city from json array.
Or you can use annotations to explicitly map city to title . Check this: https://sites.google.com/site/gson/gson-user-guide#TOC-JSON-Field-Naming-Support

Nikita already gave you the correct solution, but here it is, step by step.

I reduced your problem to this minimal test:

import com.google.gson.Gson;

public class TestGSON 
{
    public static void main( String[] args )
    {
        // that's your JSON sample
        String json = "[{\"reserve_no\":\"20\",\"city\":\"city2\",\"street\":\"street1234\",\"discription\":\"discription123\",\"date\":\"2012-10-22 04:47:54\",\"customer\":\"abc\"}]";
        // note: we tell Gson to expect an **array** of Data
        Data data[] = new Gson().fromJson(json, Data[].class);
        System.out.println(data[0]);
    }
}

The problem is that your JSON fragment is actually an array of objects, not just an object (hence the [] around it). So, you need to tell GSon it must expect an array of Data, not just a Data object. By the way, the exception that's thrown when executing your code as-is already told you so:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

unless of course it got swallowed by an empty catch block

With respect to the Data class: think twice before you override the toString method like you did here. I would drop that method and just do

System.out.println( data[0].getCity() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM