为什么我的应用程序无法在OnCreate方法上找到“com.google.gson.Gson”类?

时间:2012-06-29 01:59:47

标签: android json gson

我想用Gson解析我的JSON,我已经将Gson库添加到我的项目中。编译它时一切都很好,但是当我运行它时,我会收到错误消息日志

Could not find class 'com.google.gson.Gson', referenced from method report.weeklyflash.WeeklyFlashIdActivity.onCreate

这是使用Gson的代码:

import com.google.gson.Gson;
import report.weeklyflash.ReportResult;
import report.weeklyflash.ReportResults;



public class WeeklyFlashIdActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.list_item);

    System.out.println("oncreate");

    final TableLayout tableLayout = (TableLayout) findViewById(R.id.headerTable);

    InputStream is = null;
    String json = "";

    //http get content
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://10.80.3.73/webservice/Service1.svc/json/weeklyflash/my");
        HttpResponse response = httpclient.execute(httpget);
        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,"UTF-8"),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("log_tag", "Error converting result "+e.toString());
    }


    ReportResults reports = new Gson().fromJson(json, ReportResults.class);
    List<ReportResult> results = reports.getGetReportResult();
//bla..blaa.bblaa..

有关详细信息,请参阅以下完整代码:
My Activity code
My ReportResult Class code
My ReportResults Class code

2 个答案:

答案 0 :(得分:8)

确保将gson.jar放在libs目录中。从ADT17开始,所有外部图书馆罐子都必须去那里。

好消息是你只需将它们放在那里,工具就会把它们添加到项目中。

哦,该目录需要与srcassets等处于同一级别。

答案 1 :(得分:0)

制作&#34; libs&#34;项目根目录中的文件夹&#34; src&#34;&amp;&#34; assets&#34;保存文件夹,将jar文件放入其中,这就是全部。现在你可以使用它们了。确保撤消您尝试进行的所有更改。 :)