0

JSON配列から値を取得して表示する必要があります。以下は私が使用したコードです。

getresponseクラスはHTTPリクエストをPHPページに送信し、関連するJSON配列を取得し、パブリック変数resは返されたJSON配列を保持します。

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クラス

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();

以下は、返されるJSON配列の例です。

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

このコードは、返されたJSON配列の都市名を表示しません。誰かがコードを修正することによってこれを手伝ってくれるか、もしあればより良いまたはより簡単な方法を提案できますか?:)

4

2 に答える 2

2

Gsonは、クラスプロパティ名に基づいて、json文字列をクラスにマップします。したがって、Dataクラスには、json配列titleにマップされることになっているプロパティがあります。Gsonがjson配列からどこに配置するかを判断できるように、cityプロパティの名前をに変更する必要があります。 または、アノテーションを使用して明示的ににマップすることもできます。これを確認してください:https ://sites.google.com/site/gson/gson-user-guide#TOC-JSON-Field-Naming-Supportcitycity
citytitle

于 2012-10-22T21:30:54.267 に答える
2

ニキータはすでに正しい解決策を示しましたが、ここでは段階的に説明します。

私はあなたの問題をこの最小限のテストに減らしました:

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]);
    }
}

問題は、JSON フラグメントが実際には単なるオブジェクトではなく、オブジェクトの配列であることです (したがって、[] で囲まれています)。したがって、Data オブジェクトだけでなく、Data の配列を期待する必要があることを GSon に伝える必要があります。ちなみに、コードをそのまま実行するとスローされる例外は、すでにそう言っています。

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

catchもちろん、空のブロックに飲み込まれた場合を除きます

Data クラスに関しては、ここで行ったように toString メソッドをオーバーライドする前によく考えてください。私はその方法をやめて、ただやります

System.out.println( data[0].getCity() );
于 2012-10-22T22:49:28.783 に答える