2016-06-03 3 views
1

Я пытаюсь прочитать файл JSON, чтобы преобразовать его в объект Java, но я получаю сообщение об ошибке. Этот код ответа JSON представляет собой API. Вот моя основная деятельность. Это первый раз, когда я задаю вопрос, поэтому, пожалуйста, помогите мне.Преобразование ответа JSON в объект JAVA

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); 
} 
+0

Я также включил зависимость GSON в файле gradle –

+1

Какова ошибка, которую вы получаете. Добавьте журналы. –

+0

У вас есть ' ' в вашем 'Manifest'. –

ответ

4

Причина в том, что вы пытаетесь прочитать этот файл с вашего устройства, которое находится на вашем рабочем столе/ноутбуке.

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

И вы не можете так сделать так. Файл должен присутствовать где-то в вашем внешнем каталоге хранилища.