使用改进功能从(本地)android资产文件夹获取Json数据

我正在处理一个需要从本地android资产目录访问Json数据的项目。 我可以使用Volley Library从资源文件夹读取json数据,但我想使用Retrofit来做同样的事情。 以下是我的json文件 - myfile.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从服务器读取数据。 有什么方法可以使用改造来实现这一要求。


正如Dheerubhai写的Retrofit不用于解析JSON对象。 你可以使用GSON,看到这个线程看看如何使它与Retrofit一起工作,你可以看到这个教程。


您正试图在您的项目中实施存根。

将你的.json文件添加到res / raw / filename.json中

上面的示例显示了两个Web服务端点(/ some / web / service,/ another / web / service)的本地存根文件以及两个方案 - empty和default(默认存根没有前缀,空存根以“empty_”为前缀) )。 这些文件的内容通常是JSON。

接下来,我们编写一个自定义的HTTP客户端来从这些本地文件而不是网络中获取。 以下示例从Square的Retrofit库实现Client对象。 如果您对Retrofit不熟悉,则默认的客户端实现为OkClient。 它发出一个标准的HTTP网络请求。 我们正在编写一个自定义客户端来伪造网络请求,并从本地文件而不是网络服务器获取响应数据。

上面的示例显示了两个Web服务端点(/ some / web / service,/ another / web / service)的本地存根文件以及两个方案 - empty和default(默认存根没有前缀,空存根以“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();

模拟网络延迟和故障改造还使我们能够模拟网络延迟,变化和故障。 以下是基于我们的第二个Dev设置启用/禁用模拟网络适配器的代码:

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)
链接地址: http://www.djcxy.com/p/29511.html

上一篇: Getting Json data from (Local) android assets folder using retrofit

下一篇: Parsing Objest Data Using Volley Library in Android App