2017-04-20 71 views
0

我正在致力於一個需要從本地Android資產目錄訪問Json數據的項目。我可以使用Volley Library閱讀資產文件夾中的json數據,但我想用改裝來做同樣的事情。以下是我的json文件 - myfile.json使用改進方法從(本地)android資產文件夾獲取Json數據

{ 
    "formules": [ 
    { 
     "formule": "Linear Motion", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Constant Acceleration Motion", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Projectile Motion", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Force", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Work, Power, Energy", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Rotary Motion", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Harmonic Motion", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Gravity", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Lateral and Longitudinal Waves", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Sound Waves", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Electrostatics", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Direct Current", 
     "url": "<html><body>You scored <b>192</b> points. <img src=\"http://192.168.1.46/shanta_holdings/img/images/project-thumbs/Glasshouse-1.jpg\" alt=\"Smiley face\"/></body></html> ", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Magnetic Field", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Alternating Current", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Thermodynamics", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Hydrogen Atom", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Optics", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Modern Physics", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Hydrostatics", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    }, 
    { 
     "formule": "Astronomy", 
     "url": "https://www.google.com/", 
     "des":"Here is a description" 
    } 
    ] 
} 

我搜索了一個星期,但沒有得到任何適合的改造解決方案。我可以使用Retrofit從服務器讀取數據。有什麼方法可以使用改造來實現這一要求。

+2

我覺得Volly和改造用於其他API不從資源文件夾,使用GSON轉換JSON解析。 –

+1

我有一個問題:**爲什麼?**爲什麼你想在不應該使用Volley和Retrofit的地方使用?爲什麼你不想直接加載文件? –

回答

0

正如Dheerubhai寫道Retrofit不用於解析JSON對象。您可以使用GSON,請參見this thread以瞭解如何使其與Retrofit配合使用,您可以看到this tutorial

+0

我能夠通過改進從服務器檢索數據。你可能不清楚我的問題。我想從本地文件中檢索json數據,而不是從url中獲取數據。 –

+0

我明白了,但第一個鏈接包含從本地存儲的JSON文件中檢索數據的示例。 – gonczor

0

您正試圖在您的項目中實施存根。

添加您以.json文件到RES /生/ filename.json

上面的示例顯示了兩個Web服務端點本地存根文件 - /一些/網絡/服務/其它/網絡/服務)和兩個場景 - 空的和默認的(默認存根沒有前綴,空存根以「empty_」爲前綴)。這些文件的內容通常是JSON。

接下來我們編寫一個自定義的HTTP客戶端從這些本地文件而不是網絡中獲取。以下示例從Square的Retrofit庫實現Client對象。如果您對Retrofit不熟悉,則默認的客戶端實現爲OkClient。它發出一個標準的HTTP網絡請求。我們正在編寫一個自定義客戶端來僞造網絡請求,並從本地文件而不是網絡服務器獲取響應數據。

上面的示例顯示了兩個Web服務端點(/ some/web/service,/ another/web/service)的本地存根文件以及兩個方案 - empty和default(默認存根沒有前綴,並且空stub前綴通過「empty_」)。這些文件的內容通常是JSON。

接下來我們編寫一個自定義的HTTP客戶端從這些本地文件而不是網絡中獲取。以下示例從Square的Retrofit庫實現Client對象。如果您對Retrofit不熟悉,則默認的客戶端實現爲OkClient。它發出一個標準的HTTP網絡請求。我們正在編寫一個自定義客戶端來僞造網絡請求,並從本地文件而不是網絡服務器獲取響應數據。

public class LocalStubClient implements Client { 
    private Context context; 
    private String scenario; 

    public LocalStubClient(Context context, String scenario) { 
     this.context = context; 
     this.scenario = scenario; 
    } 

    public LocalStubClient(Context context) { 
     this.context = context; 
    } 

    public void setScenario(String scenario) { 
     this.scenario = scenario; 
    } 

    @Override 
    public Response execute(Request request) throws IOException { 
     //get resource id for local file 
     String fileName = createFilename(request, scenario); 
     int resourceId = getResourceId(fileName); 
     if (resourceId == 0) { //fallback to default filename 
      fileName = createFilename(request, null); 
      resourceId = getResourceId(fileName); 
      if (resourceId == 0) { 
       throw new IOException("Could not find res/raw/" + fileName + ".stub"); 
      } 
     } 

     //get input stream & mime for local file 
     InputStream inputStream = context.getResources().openRawResource(resourceId); 
     String mimeType = URLConnection.guessContentTypeFromStream(inputStream); 

     //wrap local stream in retrofit objects 
     TypedInput body = new TypedInputStream(mimeType, inputStream.available(), inputStream); 
     Response response = new Response(request.getUrl(), 200, "Stub from res/raw/" + fileName, new ArrayList<Header>(), body); 
     return response; 
    } 

    private String createFilename(Request request, String scenario) throws IOException { 
     URL requestedUrl = new URL(request.getUrl()); 
     String requestedMethod = request.getMethod(); 
     String prefix = scenario == null ? "" : scenario + "_"; 
     String filename = prefix + requestedMethod + requestedUrl.getPath(); 
     filename = filename.replace("/", "_").replace("-", "_").toLowerCase(); 
     return filename; 
    } 

    private int getResourceId(String filename) { 
     return context.getResources().getIdentifier(filename, "raw", context.getPackageName()); 
    } 

    private static class TypedInputStream implements TypedInput { 
     private final String mimeType; 
     private final long length; 
     private final InputStream stream; 

     private TypedInputStream(String mimeType, long length, InputStream stream) { 
      this.mimeType = mimeType; 
      this.length = length; 
      this.stream = stream; 
     } 

     @Override 
     public String mimeType() { 
      return mimeType; 
     } 

     @Override 
     public long length() { 
      return length; 
     } 

     @Override 
     public InputStream in() throws IOException { 
      return stream; 
     } 
    } 
} 

最後,我們檢查我們的「後端環境」設置來確定是否應該用我們的LocalStubClient或默認OkClient:

RestAdapter.Builder builder = new RestAdapter.Builder(); 

String selectedBackend = getSharedPreference(R.string.pref_backend, ""); 
switch (Integer.parseInt(selectedBackend)) { 
    case R.string.test_server: 
    case default: 
     builder.setClient(new OkClient()); 
     builder.setEndpoint("http://test.api.mydomain.com"); 
     break; 
    case R.string.demo_server: 
     builder.setClient(new OkClient()); 
     builder.setEndpoint("http://demo.api.mydomain.com"); 
     break; 
    case R.string.default_local_stubs: 
     builder.setClient(new LocalStubClient(app)); 
     break; 
    case R.string.empty_local_stubs: 
     builder.setClient(new LocalStubClient(app, "empty")); 
     break; 
} 

RestAdapter adapter = builder.build(); 

模擬網絡延遲和失敗 改造也使我們能夠模擬網絡延遲,差異和故障。這裏的代碼啓用/禁用基於我們的第二個開發設置一個模擬的網絡適配器:

RestAdapter.Builder builder = new RestAdapter.Builder(); 

//... 

RestAdapter adapter = builder.build(); 

if (getSharedPreference(R.string.pref_mock_network, false)) { 
    MockRestAdapter mockRestAdapter = MockRestAdapter.from(adapter); 
    mockRestAdapter.setDelay(1000); 
    mockRestAdapter.setVariancePercentage(50); 
    mockRestAdapter.setErrorPercentage(10); 
    return mockRestAdapter.create(serviceType, adapter.create(serviceType)); 
} 
return adapter.create(serviceType) 
+0

感謝您的回覆。讓我試試你的解決方案,我會讓你知道。 –

相關問題