Getting Json data from (Local) android assets folder using retrofit
I am working on a project which required to access Json data from the local android assets directory . I can able to read json data from assets folder using Volley Library but i want to do the same thing using Retrofit . Below is my json file - 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"
}
]
}
I have search over for a week but didn't get any proper solution for retrofit. I can able to read data from server using Retrofit. Is there any way to achieve the requirement using retrofit.
As Dheerubhai wrote Retrofit isn't used for parsing JSON objects. You can use GSON, see this thread to see how to make it work with Retrofit, you can see this tutorial.
You are trying to implement stub in your project.
Add your .json file into res/raw/filename.json
The example above shows local stub files for two web service endpoints - /some/web/service, /another/web/service) and two scenarios - empty and default (where default stubs have no prefix and empty stubs are prefixed by “empty_”). The contents of these files is typically JSON.
Next we write a custom HTTP client to fetch from these local files instead of the network. The following example implements the Client object from Square's Retrofit library. If you're not familiar with Retrofit, the default Client implementation is OkClient. It makes a standard HTTP network request. We're writing a custom client to fake a network request and get the response data from a local file instead of a network server.
The example above shows local stub files for two web service endpoints - /some/web/service, /another/web/service) and two scenarios - empty and default (where default stubs have no prefix and empty stubs are prefixed by “empty_”). The contents of these files is typically JSON.
Next we write a custom HTTP client to fetch from these local files instead of the network. The following example implements the Client object from Square's Retrofit library. If you're not familiar with Retrofit, the default Client implementation is OkClient. It makes a standard HTTP network request. We're writing a custom client to fake a network request and get the response data from a local file instead of a network server.
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;
}
}
}
Finally we check our “Backend Environment” setting to determine if we should use our LocalStubClient or the default 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();
Simulate network delays and failures Retrofit also allows us to simulate network delays, variance, and failures. Here's code to enable/disable a mock network adapter based on our second Dev setting:
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/29512.html