将JSON响应转换为JAVA对象

时间:2016-06-03 18:26:10

标签: android json gson

我正在尝试读取JSON文件以将其转换为Java对象但我收到错误。此JSON响应代码来自API。这是我的主要活动。这是我第一次提出问题所以请帮助我。

package com.example.ahsan.jsontogson;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import java.io.FileReader;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String mPath = "Json.txt";
private QuoteBank mQuoteBank;
private List<String> mLines;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Gson gson = new Gson();
    // 1. i am getting error on this line source file is not located error
    QuoteBank staff = gson.fromJson(new FileReader("D:\\JSON.txt"),    QuoteBank.class);
    // 2. JSON to Java object, read it from a Json String.
    String jsonInString = "{'name' : 'mkyong'}";
    Staff staff = gson.fromJson(jsonInString, Staff.class);
    // JSON to JsonElement, convert to String later.
    JsonElement json = gson.fromJson(new FileReader("D:\\file.Json"), JsonElement.class);
    String result = gson.toJson(json);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

1 个答案:

答案 0 :(得分:4)

原因是您尝试从桌面/笔记本电脑上的设备读取该文件。

 QuoteBank staff = gson.fromJson(new FileReader("D:\\JSON.txt"),    QuoteBank.class); //D drive path

你不能以任何方式这样做。 该文件应存在于设备外部存储目录中的某个位置。