如何从json(或xml)字符串中获取键值?

时间:2011-11-02 21:40:33

标签: java android mobile

在android应用程序中,我得到一个xml或json字符串返回,但是,我似乎无法通过输入密钥以任何方式弄清楚如何从字符串中获取值。

在PHP中,你只需要使用类似$ myArray ['parent'] ['child']的东西,但我不知道它在java中是如何工作的。

任何想法都将不胜感激! (更多XML和JSON的例子;))

3 个答案:

答案 0 :(得分:2)

这就是我要做的事情:

  1. 找到一个XML / JSON库(有吨)(j {的google-gson
  2. 阅读文档以查找parse方法((new JsonParser()).parse(text)
  3. 阅读文档以了解返回值是什么(JsonElement
  4. 决定您要对解析后的数据(myJsonObj.get(...)
  5. 做什么
  6. 编写代码

答案 1 :(得分:1)

 public class parsingjsontest2 extends Activity {
/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(main);

String str = connect("http://rentopoly.com/ajax.php?query=Bo"));
System.out.println("String::"+str);
}

}

private String connect(String url) {

// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;

    // return string
    String returnString = null;

    try {

       // Open the webpage.
        response = httpclient.execute(httpget);

        if(response.getStatusLine().getStatusCode() == 200){
            // Connection was established. Get the content. 

            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();

                // Load the requested page converted to a string into a JSONObject.
                JSONObject myAwway = new JSONObject(convertStreamToString(instream));

                // Get the query value'
                String query = myAwway.getString("query");

                **// Make array of the suggestions
                JSONArray suggestions = myAwway.getJSONArray("suggestions");

                // Build the return string.
                returnString = "Found: " + suggestions.length() + " locations for " + query;
                for (int i = 0; i < suggestions.length(); i++) {
                    returnString += "\n\t" + suggestions.getString(i);
                }

                // Cose the stream.
                instream.close();
            }
        }
        else {
            // code here for a response othet than 200.  A response 200 means the webpage was ok
            // Other codes include 404 - not found, 301 - redirect etc...
            // Display the response line.
            returnString = "Unable to load page - " + response.getStatusLine();
        }
    }
    catch (IOException  ex) {
        // thrown by line 80 - getContent();
        // Connection was not established
        returnString = "Connection failed; " + ex.getMessage();
    }
    catch (JSONException ex){
        // JSON errors
        returnString = "JSON failed; " + ex.getMessage();
    }
    return returnString;
}

private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

答案 2 :(得分:0)

由于您没有指定您尝试阅读的是哪种xml,我正在根据我的知识回答。

在Android中,如果您正在讨论布局和strings.xml文件,则使用点(。)运算符,如R.string.appname。

如果这不是您想要的,请发布有关您的具体问题的更多详细信息。