0

ここから非常に単純な JSON 形式のデータを取得していますが、次のようになります。

{
    "date" : "2013-11-01",
    "gold" : "1317.29",
    "silver" : "21.90",
    "platinum" : "1458.00"
}

「gold」タグの値を取得するだけです。

私のコードは次のとおりです。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class JsonActivity extends Activity {

static String jsonUrl = "http://services.packetizer.com/spotprices/?f=json";
static String gold = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_json);
    new MyAsyncTask().execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.json, menu);
    return true;
}
private class MyAsyncTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... arg0) {
        DefaultHttpClient httpCl = new DefaultHttpClient(new    

   BasicHttpParams());
        HttpPost httpP = new HttpPost(jsonUrl);
        httpP.setHeader("Content-type", "application/json");
        InputStream in = null;
        String result = null;
        try {
            HttpResponse response = httpCl.execute(httpP);
            HttpEntity entity = response.getEntity();
            in = entity.getContent();
            BufferedReader reader = new BufferedReader(new 
                                            InputStreamReader(in, "UTF-8"), 8);
            StringBuilder sbuilder = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
                sbuilder.append(line + "\n");
            }
            result = sbuilder.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(in != null)
                    in.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(result);
            gold = jsonObj.getString("gold");
        }
        catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        TextView goldTV = (TextView)findViewById(R.id.goldPrice);
        goldTV.setText("good price with Json" + gold);
        super.onPostExecute(result);
    }



}
}

ただし、実行すると、String gold常に返されますnull。私はそれを理解できませんでした。なぜですか?誰が何が問題だったのか教えてもらえますか? ありがとう

更新 スクリーンショットが追加されました: ここに画像の説明を入力

4

3 に答える 3

1

あなたはやっていjsonObj.getString("gold");ます..今、このjsonオブジェクトから文字列を取得しようとしていますが、jsonには、次のようなメインの親オブジェクトはありません:-

{ 
  "Android" :
            [
                {
                   "date" : "2013-11-01",
                   "gold" : "1317.29",
                   "silver" : "21.90",
                   "platinum" : "1458.00"
                }
            ] 
}

ここで、Android は jsonobject であり、getstring メソッドを呼び出すと、文字列変数で金の値を取得します。これらの 2 つのチュートリアルを実行すると、次のことが理解できます:-

ローカルからの Json チュートリアル

URL からの Json チュートリアル

于 2013-11-03T07:35:09.170 に答える
1

このコードをあなたのコードに置き換えてください

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class JsonActivity extends Activity {

static String jsonUrl = "http://services.packetizer.com/spotprices/?f=json";
static String gold = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_json);
    new MyAsyncTask().execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.json, menu);
    return true;
}
private class MyAsyncTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... arg0) {
        DefaultHttpClient httpCl = new DefaultHttpClient(new    

   BasicHttpParams());
        HttpPost httpP = new HttpPost(jsonUrl);
        httpP.setHeader("Content-type", "application/json");
        InputStream in = null;
        String result = null;
        try {
            HttpResponse response = httpCl.execute(httpP);
            HttpEntity entity = response.getEntity();
            in = entity.getContent();
            BufferedReader reader = new BufferedReader(new 
                                            InputStreamReader(in, "UTF-8"), 8);
            StringBuilder sbuilder = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
                sbuilder.append(line + "\n");
            }
            result = sbuilder.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(in != null)
                    in.close();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }


        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        if(!TextUtils.isEmpty(result))
        {
        JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(result);
            gold = jsonObj.getString("gold");
        }
        catch (JSONException e) {
            e.printStackTrace();
        } 
        TextView goldTV = (TextView)findViewById(R.id.goldPrice);
        goldTV.setText("good price with Json" + gold);
        }
        else
        {
           Toast.makeText(this,"response is null",Toast.LENGTH_LONG);
        }
        super.onPostExecute(result);
    }



}
}
于 2013-11-03T07:36:14.430 に答える
1

jsonObj が null かどうかを確認します。null の場合は、おそらく次のようなものを使用する必要があります。

JSONArray jsonArray;
JSONObject parent;
    try {
        jsonArray = new JSONArray(result);
        parent = jsonArray.getJsonObject("ParentObject");
        gold = parent.getString("gold");
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
于 2013-11-03T08:23:04.273 に答える