0

我在这里发帖是为了解决我自己的项目问题。

我想从我的 Android 应用程序连接到我的网络服务,并将这些信息获取到好的来源。我正在使用 JSON 文件(非常好),但只包含 JSON 对象。

我使用了这个非常好的来源(在他的例子中工作得很好):http ://www.androidhive.info/2012/01/android-json-parsing-tutorial/

您可以查看我的 JSON 文件:

[
    {
        "id": "2",
        "title": "Printemps du cinema",
        "content": "Decouvrez plein de nouveaux films durant la semaine du printemps du cinema.",
        "date": "2012-07-04",
        "author": "Nicolas  Jeannin",
        "zone": "Mandelieu",
        "area": "Cannes"
    },
    {
        "id": "4",
        "title": "Festival de Cannes",
        "content": "Venez assister a la montee des marches du prestigieux festival !",
        "date": "2012-05-26",
        "author": "Nicolas Teboul",
        "zone": "Cannes",
        "area": "Cannes"
    }
]

我尝试使用他的方法使其运行,但使用由 1 个元素组成的 JSON 数组。我总是有类似的错误:

“解析数据时出错 org.json.Excption:Value[{"content":".........}] ..无法转换为 JSONObject。”

您可以在下面查看我的活动:

public class AndroidJSONParsingActivity extends ListActivity 
{

    // url to make request
    private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
    //private static String url = "http://twitter.com/statuses/public_timeline.json";
    //private static String url = "http://api.androidhive.info/contacts/";
    
    //JSON names
    private static final String TAG_content = "content";
    private static final String TAG_zone = "zone";
    private static final String TAG_id = "id";
    private static final String TAG_area = "area";
    private static final String TAG_title = "title";
    private static final String TAG_date = "date";
    private static final String TAG_author = "author";
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Hashmap for ListView
        ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
        
        JSONArray event = null; 
        
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();
        
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        
        try {
                // Getting Array of Contacts
                event = json.getJSONArray("");
                
                JSONObject c = event.getJSONObject(0);
        
                // Storing each json item in variable
                
                String id = c.getString(TAG_id);
                String title = c.getString(TAG_title);
                String content = c.getString(TAG_content);
                String date = c.getString(TAG_date);
                String author = c.getString(TAG_author);
                String zone = c.getString(TAG_zone);
                String area = c.getString(TAG_area);
                
                
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                
                // adding each child node to HashMap key => value
                map.put(TAG_content, content);
                map.put(TAG_title, title);
                map.put(TAG_author, author);

                // adding HashList to ArrayList
                newsList.add(map);
            }
        catch (JSONException e) {
            e.printStackTrace();
        }
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, newsList,R.layout.list_item,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
        setListAdapter(adapter);
        
        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
                
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_content, name);
                in.putExtra(TAG_title, cost);
                in.putExtra(TAG_author, description);
                startActivity(in);

            }
        });
    }

}

这是 JSONParser :

package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String jsonstr = "";
 
    // constructor
    public JSONParser() {
    }
 
    public JSONObject getJSONFromUrl(String url) {
 
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            //HttpGet httpGet = new HttpGet(url);
            
            //HttpResponse httpResponse = httpClient.execute(httpGet);
            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();
            jsonstr = 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(jsonstr);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing de Mon fichier: " + e.toString());
        }
 
        // return JSON String
        return jObj;
     }
}

感谢帮助我的人。:)

4

1 回答 1

2

这是因为您的 JSON 定义了一个 JSON 数组,并且您尝试将其解析为 JSON 对象 - 在您的解析器类中将其更改为 JSONArray,您会没事的。

另一个问题是 memorz 管理 - 您正在重新分配字符串并使用 android.json 提供的 vanilla JSON 解析器进行解析。这可行,但内存消耗严重且分配量很大——对于更大的数据来说相当慢。改用拉解析器(如 GSON,缩小版只有 16K)

您还可以考虑使用某种数据绑定从 JSON 中创建 java 对象 - 您可以获取我的库(也可以在 maven Central 上找到):

https://github.com/ko5tik/jsonserializer

然后它会很简单:

       InputStream inputStream = getResources().openRawResource(preferences.getRecognitionConfig());
        InputStreamReader reader = new InputStreamReader(inputStream);


        JsonReader jreader = new JsonReader(reader);          
        jreader.setLenient(true);
        final RecognitionDataContainer recognitionContainer = JSONUnmarshaller.unmarshall(jreader, RecognitionDataContainer.class);

        reader.close();

(RecognitionDataContainer 是类似于 JSON 结构的顶级对象)

于 2012-07-11T19:58:56.650 回答