1

http://docs.blackberry.com/sampledata.json

这是我的 Web 服务,我想解析和检索车辆类型、车辆颜色、燃料、名称、体验点、踏步类型。

public class MainActivity extends Activity {

    private static String url="http://maps.googleapis.com/maps/api/directions/json?origin=Tamil%20ndau,Salem&destination=Tamil%20nadu,%20salem&region=in&sensor=false";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        JSONObject json=JSONParser.getJSONfromURL(url);  // here i am able to read content of that web service 
    }
} catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }

请告诉我如何获得价值?我无法为 Json 对象和 Json 数组选择节点。请告诉我下一步我必须做什么,以便我可以检索该值。我是 Json 解析和 android 的新手。请帮我。

4

4 回答 4

0
try{
 HttpGet request = new HttpGet(loginUrl);
 HttpResponse response = httpClient.execute(request);
 entityResponse = response.getEntity();
 result = EntityUtils.toString(entityResponse);  


JSONArray array = object.getJSONArray("routes"); 


---Parsing first jsonArray     
  JSONObject routes = array.getJSONObject(0);


---(parsing first jsonarray object)
  String bounds= routes.getString("bounds"); 


-- parsing second josn Array  
  JSONArray legs = routes.getJSONArray("legs"); 


--- (parsing second jsonarray object)   

JSONObject steps = legs.getJSONObject(0); 

String distance= routes.getString("distance"); 


--- parsing third json Array
  JSONArray legs1 = steps.getJSONArray("steps"); 
  for(int i = 0; i < legs1.length(); i++){
  JSONObject steps1 = legs1.getJSONObject(i);


--parsing third jsonarray objecct      
  String htMlVale = steps1.getString("html_instructions").toString(); 


-- parsing inside third jsonarray of jsonarray   
  JSONObject distance             =  steps1.getJSONObject("distance");
          String sDistance                =  distance.getString("text");()



        }
} 
于 2012-09-07T05:21:12.150 回答
0

你可以使用这个类:

只需制作此类的对象并调用方法即可!

public class JSONParser {


    private static String result;
    private static String resultArr;

    public static String getJSONArr (String json,String tag1,int arrNum)
    {

        try {
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                if(i==arrNum){
                    JSONObject row = array.getJSONObject(i);
                resultArr = row.getString(tag1);
                }
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return resultArr;

    }

    public static String getJSONObj (String json,String tag1)
    {
        try {
            JSONObject jObj =  new JSONObject(json);

            if(jObj.has(tag1))
                result = jObj.getString(tag1);
            else
                Log.d("JSON ERROR", "tag not found");

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }
}
于 2012-09-07T05:22:06.840 回答
-1

给定的 url 返回一个 JSONArray,所以方法 getJSONFromUrl 应该返回 JSONArray..

try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIME_OUT);
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);

        //prepare the HTTP GET call 
        HttpGet httpget = new HttpGet(urlString);
        //get the response entity
        HttpEntity entity = httpClient.execute(httpget).getEntity();

        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            //return the JSON response
            JSONArray array = new JSONArray(response.trim());
                for(int i = 0 ; i < array.length() ; i++) { //get the current JSON object
                    JSONObject object = (JSONObject) array.get(i);
                    String vehicleType = object.getString("vehicleType");
                    ......
                 }
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
于 2012-09-06T12:05:55.283 回答
-1

可能是这段代码对你有帮助

public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONArray jArray = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag get data string ",
                "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONArray(result);
    } catch (JSONException e) {
        Log.e("log_tag create object ",
                "Error parsing data " + e.toString());
    }

    return jArray;
}
  }

这是解析代码示例,您可以更改它。

public class Main extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);

    JSONArray json = JSONfunctions
            .getJSONfromURL("http://docs.blackberry.com/sampledata.json");

    for (int i = 0; i < json.length(); i++) {

        try {
            Log.e("json names vehicleType", ""
                    + json.getJSONObject(i).getString("vehicleType"));
            Log.e("json names vehicleColor", ""
                    + json.getJSONObject(i).getString("vehicleColor"));
            Log.e("json names fuel",
                    "" + json.getJSONObject(i).getString("fuel"));
            Log.e("json names treadType", ""
                    + json.getJSONObject(i).getString("treadType"));

            Log.e("json names approvedOperators",
                    ""
                            + json.getJSONObject(i).getJSONArray(
                                    "approvedOperators"));

            JSONArray array = json.getJSONObject(i).getJSONArray(
                    "approvedOperators");
            for (int j = 0; j < array.length(); j++) {

                Log.e("json names approvedOperators name ", ""
                        + array.getJSONObject(j).getString("name"));
                Log.e("json names approvedOperators experience ",
                        ""
                                + array.getJSONObject(j).getString(
                                        "experiencePoints"));

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
}
于 2012-09-07T05:20:07.673 回答