2

我正在尝试将 API 集成到我正在编写的 android 应用程序中,但是我在尝试获取 JSON 数组时遇到了噩梦。该 API 有一个返回 JSON 数组的 URL,但在我不知道它是如何工作或如何操作之前从未使用过 JSON。

我已经查看并找到了大量的示例,但没有什么可以解释它为什么/如何完成的。任何帮助理解这一点将不胜感激。

这就是我最终得到的结果,再次对 JSON 不了解,这是我在黑暗中的一次尝试(使用示例/教程作为指导)......但它不起作用:(

import org.json.*;          
//Connect to URL
        URL url = new URL("URL WOULD BE HERE");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.connect();

//Get Data from URL Link
        int ok = connection.getResponseCode();
        if (ok == 200) {
        String line = null;
        BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();

        while ((line = buffer.readLine()) != null)
          sb.append(line + '\n');
        //FROM HERE ON I'm Kinda Lost & Guessed
        JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
        JSONArray array = (JSONArray)obj.get("response");
        for (int i=0; i < array.size(); i++) {
          JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
          System.out.println(list.get("name")); //Used to debug
        }
      }

更新/解决方案: 所以,事实证明代码没有任何问题。我错用了我认为它会返回的东西。我认为这是一个 JSONObject 数组。实际上,它是一个包裹在一个数组中的 JSONObjects,包裹在一个 JSONObject 中。

对于那些感兴趣/有类似问题的人,这就是我最终得到的。我把它分成两种方法。首先连接/下载,然后:

private String[] buildArrayList(String Json, String Find) {
            String ret[] = null;
            try {
            JSONObject jObject = new JSONObject(Json);
            JSONArray jArray = jObject.getJSONArray("response");
            ret = new String[jArray.length()];

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

            JSONObject json_data = jArray.getJSONObject(i);
            String var = json_data.getString(Find);
            ret[i] = var;
            }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ret;  
  }
4

3 回答 3

0

好的,我的朋友,我用下面的代码在我的应用程序中解决了同样的问题:

1.- 处理 Http 请求的类:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
        //Log.e("JSONObject(JSONParser1):", json);
    } catch (Exception e) {
        Log.e("Buffer Error json1" +
                "", "Error converting result json1:" + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
        jObj1 = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
    }
    // return JSON String
    return jObj;
}
}

后来,一个类来处理 json 信息(数组、对象、字符串等......)

public class ListViewer extends ListActivity{

TextView UserName1;
TextView LastName1;

 // url to make request
private static String url = "http://your.com/url";

// JSON Node names
public static final String TAG_COURSES = "Courses";    //JSONArray
//public static final String TAG_USER = "Users";    //JSONArray -unused here.

//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating";  //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";


public static final String TAG_STATUS = "Status";  //Object from Courses    
public static final String TAG_FIRSTNAME = "FirstName";  //Object from User
public static final String TAG_LASTNAME = "LastName";  //Object from User 

// contacts JSONArray
JSONArray Courses = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lay_main);

    // Hashmap for ListView
    final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance (json2)
    JSONParser2 jParser2 = new JSONParser2();

    // getting JSON string from URL json2
    final JSONObject json2 = jParser2.getJSONFromUrl(url);

            try {

                // Getting Array of Contacts
                Courses = json2.getJSONArray(TAG_COURSES);
                // looping through All Courses      
                for(int i = 0; i < Courses.length(); i++){
                    JSONObject courses1 = Courses.getJSONObject(i);

                    // Storing each json item in variable
                    String courseID = courses1.getString(TAG_COURSEID);
                    //String status = courses1.getString(TAG_STATUS);

                    String Title = courses1.getString(TAG_TITLE);

                    String instructor = courses1.getString(TAG_INSTRUCTOR);
                    String length = courses1.getString(TAG_LENGTH);
                    String rating = courses1.getString(TAG_RATING);
                    String subject = courses1.getString(TAG_SUBJECT);
                    String description = courses1.getString(TAG_DESCRIPTION);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_COURSEID,courseID);
                    map.put(TAG_TITLE, Title);
                    map.put(TAG_INSTRUCTOR, instructor);
                    map.put(TAG_LENGTH, length);
                    map.put(TAG_RATING, rating);
                    map.put(TAG_SUBJECT, subject);
                    map.put(TAG_DESCRIPTION, description);

                    //adding HashList to ArrayList
                    coursesList.add(map);
                }} //for Courses
                catch (JSONException e) {
                e.printStackTrace();
                }

     //Updating parsed JSON data into ListView
    ListAdapter adapter = new SimpleAdapter(this, coursesList,
            R.layout.list_courses,
            new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
                    R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        //@Override  --------check this override for onClick event---------
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            // getting values from selected ListItem
            String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
            String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
            String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
            String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
            String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
            String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
            String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleListItem.class);

            in.putExtra(TAG_COURSEID, courseID);
            in.putExtra(TAG_TITLE, Title);
            in.putExtra(TAG_INSTRUCTOR, instructor);
            in.putExtra(TAG_LENGTH, length);
            in.putExtra(TAG_RATING, rating);
            in.putExtra(TAG_SUBJECT, subject);
            in.putExtra(TAG_DESCRIPTION, description);
            startActivity(in);
        }
    });//lv.SetOnclickListener                      
}//onCreate
 }// Activity

在这种情况下,我会得到数组,对象......希望这能给你一些想法......

于 2012-05-06T06:21:49.207 回答
0

在这里你用JSONValue.parse()的是无效的。

Insted 的那一行写下这段代码:

JSONObject obj = new JSONObject(<String Value>);
于 2012-05-06T05:22:35.873 回答
0

1) 使用 webservice 下载你需要的 Json 字符串

2) 使用Google Gson将其转换为您想要的对象

Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
于 2012-05-06T05:08:36.360 回答