2017-09-13 4 views
-4

私はvalues配列の一つの値を取得し、日食中のTextViewの上に載せていきたいと思いますこのようなJSONの解析方法は?

{ 
    "status":200, 
    "message":"ok", 
    "response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0] 
    } 
} 

のようなJSONデータ・フォーマットを持っています。日食で自分のコードを見てください

protected void onPostExecute (String result){ 
try { 
JSONobject json = new JSONObject(result); 
tv.setText(json.toString(1)); 
}catch (JSONException e){ 
e.printStackTrace(); 
} 
} 
+2

あなたのコードは、いくつかの部分が欠けているように見えます。 'try'はどこにあり、関数はどこで閉じますか? – nalyd88

答えて

0

jsonの解析にはjacksonライブラリを使用できます。

ObjectMapper mapper = new ObjectMapper(); 
Map map = mapper.readTree(json); 
map.get("key"); 

あなたはJSONはマップを取得するためにtyperefを使用してreadValueで行く他JSONObjectクラスのインスタンスであるわかっている場合は、readTreeを使用することができます。

1

あなたはGSON

を使用することができ、あなたの応答を

public class Response{ 
    private int result; 
    private double time; 
    private ArrayList<Integer> values; 

    // create SET's and GET's 
} 

をPOJOを作成し、あなたが望むオブジェクトを作成するGSONを使用しています。

protected void onPostExecute (String result){ 
    try { 
    Gson gson = new GsonBuilder().create(); 
    Response p = gson.fromJson(result, Response.class); 
    tv.setText(p.getValues()); 
    }catch (JSONException e){ 
    e.printStackTrace(); 
    } 
} 
+0

ありがとうjoao86の、あなたのコードが助けてきた、それは働いているが、私はインデックスで値の配列を取得したい。私は何のためにこれを行うべきですか?どうすればいいですか? –

+0

@ ahsanasha07 '値を配列で取得するのはどういう意味ですか? '配列の特定の位置に値を取得する場合は、単に 'p.getValues()。get(position)'を実行してください。 – joao86

+0

はい、私は配列の特定の位置に値を取得します。私はp.getValues()を試してください。get(position)not working。 –

0
protected void onPostExecute (String result){ 
    try { 
    JSONObject json = new JSONObject(result); 
    JSONObject resp = json.getJSONObject("response"); 
JSONArray jarr = resp.getJSONArray("values"); 
    tv.setText(jarr.get(0).toString(1)); 
    }catch (JSONException e){ 
    e.printStackTrace(); 
    } 
    } 
+0

まだ動作していません –

+0

おかげで、今働いています。私は単にtv.setText(jarr.get(0).toStirng(1))を変更します。にtv.setText(jarr.get(0).toString()); done –

+0

助けてくれたら、私に投票することができます。または、それを回答としてマークします。 –

関連する問題