Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/196.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中解析JSON?_Android_Json_Parsing - Fatal编程技术网

如何在Android中解析JSON?

如何在Android中解析JSON?,android,json,parsing,Android,Json,Parsing,如何在Android中解析JSON提要?我为您编写了一个简单的示例,并对源代码进行了注释。该示例显示了如何获取实时json并解析为JSONObject以进行细节提取: try{ // Create a new HTTP Client DefaultHttpClient defaultClient = new DefaultHttpClient(); // Setup the get request HttpGet httpGetRequest = new Http

如何在Android中解析JSON提要?

我为您编写了一个简单的示例,并对源代码进行了注释。该示例显示了如何获取实时json并解析为
JSONObject
以进行细节提取:

try{
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient();
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet("http://example.json");

    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    String json = reader.readLine();

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json);

} catch(Exception e){
    // In your production code handle any errors and catch the individual exceptions
    e.printStackTrace();
}

一旦您拥有了
JSONObject
,请参阅以获取有关如何提取所需数据的详细信息。

Android拥有解析内置json所需的所有工具。下面是一个例子,不需要GSON或类似的东西

获取您的JSON:

JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
假设您有一个json字符串

String result = "{\"someKey\":\"someValue\"}";
创建一个:

JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
如果您的json字符串是数组,例如:

String result = "[{\"someKey\":\"someValue\"}]"
然后您应该使用如下所示的
JSONArray
,而不是
JSONObject

获取特定字符串

String aJsonString = jObject.getString("STRINGNAME");
long aJsonLong = jObject.getLong("LONGNAME");
获取特定的布尔值

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
获取特定整数

int aJsonInteger = jObject.getInt("INTEGERNAME");
获取特定的long

String aJsonString = jObject.getString("STRINGNAME");
long aJsonLong = jObject.getLong("LONGNAME");
以获得特定的双精度

double aJsonDouble = jObject.getDouble("DOUBLENAME");
要获取具体信息:

JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
从数组中获取项目

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}
for(int i=0;i
  • 编写JSON解析器类

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                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();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  • 解析JSON数据
    一旦创建了解析器类,接下来的事情就是知道如何使用该类。下面我将解释如何使用parser类解析json(在本例中采用)

    2.1。将所有这些节点名称存储在变量中:在contacts json中,我们有名称、电子邮件、地址、性别和电话号码等项。所以第一件事是将所有这些节点名存储在变量中。打开主活动类并声明将所有节点名称存储在静态变量中

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    
    2.2。使用解析器类获取
    JSONObject
    ,并循环遍历每个json项。下面我创建了一个
    JSONParser
    类的实例,并使用for循环遍历每个json项,最后将每个json数据存储在变量中

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
    //创建JSON解析器实例
    JSONParser jParser=新的JSONParser();
    //从URL获取JSON字符串
    JSONObject json=jParser.getJSONFromUrl(url);
    试一试{
    //获取联系人数组
    contacts=json.getJSONArray(TAG_contacts);
    //通过所有触点循环
    对于(int i=0;i

  • 您好,我已将此文件放入,但出现错误我已导入所有内容,但仍然存在问题您需要将上面的代码块包装在一个try catch中,我已编辑代码以反映这一点。如果检索到的文件包含换行符,
    readLine()
    失败。不知道Android,但在普通Java下,我使用:EDIT:在android下工作:sdk中嵌入了一个json解析器。请看下面的链接,您可以从中获得使用改装的数据。您也可以在android中使用gson:当您收到一个JSONArray时,如果您尝试使用JSONObject jObject=new JSONObject(result),您将得到一个关于解析的示例。在这种情况下,JSONArray jArray=new-JSONArray(result)可以工作