मान लीजिए कि मेरे पास मेरे एप्लिकेशन में कच्चे संसाधन फ़ोल्डर में JSON सामग्री के साथ एक फ़ाइल है। मैं इसे ऐप में कैसे पढ़ सकता हूं, ताकि मैं JSON को पार्स कर सकूं?
जवाबों:
देखें openRawResource । कुछ इस तरह काम करना चाहिए:
InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String jsonString = writer.toString();
\res\json_file.jsonफ़ोल्डर के अंदर या अंदर \res\raw\json_file.json?
getResources()कहा जा सकता है? कच्चे संसाधन फ़ाइल को कहाँ जाना चाहिए? बिल्ड टूल्स बनाने के लिए आपको किस कन्वेंशन का पालन करना चाहिए R.raw.json_file?
Kotlin अब Android के लिए आधिकारिक भाषा है, इसलिए मुझे लगता है कि यह किसी के लिए उपयोगी होगा
val text = resources.openRawResource(R.raw.your_text_file)
.bufferedReader().use { it.readText() }
मैंने एक ऑब्जेक्ट बनाने के लिए @ kabuko के उत्तर का उपयोग किया, जो कि JSON फ़ाइल से लोड होता है , संसाधन से Gson का उपयोग करते हुए :
package com.jingit.mobile.testsupport;
import java.io.*;
import android.content.res.Resources;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* An object for reading from a JSON resource file and constructing an object from that resource file using Gson.
*/
public class JSONResourceReader {
// === [ Private Data Members ] ============================================
// Our JSON, in string form.
private String jsonString;
private static final String LOGTAG = JSONResourceReader.class.getSimpleName();
// === [ Public API ] ======================================================
/**
* Read from a resources file and create a {@link JSONResourceReader} object that will allow the creation of other
* objects from this resource.
*
* @param resources An application {@link Resources} object.
* @param id The id for the resource to load, typically held in the raw/ folder.
*/
public JSONResourceReader(Resources resources, int id) {
InputStream resourceReader = resources.openRawResource(id);
Writer writer = new StringWriter();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceReader, "UTF-8"));
String line = reader.readLine();
while (line != null) {
writer.write(line);
line = reader.readLine();
}
} catch (Exception e) {
Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e);
} finally {
try {
resourceReader.close();
} catch (Exception e) {
Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e);
}
}
jsonString = writer.toString();
}
/**
* Build an object from the specified JSON resource using Gson.
*
* @param type The type of the object to build.
*
* @return An object of type T, with member fields populated using Gson.
*/
public <T> T constructUsingGson(Class<T> type) {
Gson gson = new GsonBuilder().create();
return gson.fromJson(jsonString, type);
}
}
इसका उपयोग करने के लिए, आप निम्न जैसा कुछ करेंगे (उदाहरण एक में है InstrumentationTestCase):
@Override
public void setUp() {
// Load our JSON file.
JSONResourceReader reader = new JSONResourceReader(getInstrumentation().getContext().getResources(), R.raw.jsonfile);
MyJsonObject jsonObj = reader.constructUsingGson(MyJsonObject.class);
}
implementation 'com.google.code.gson:gson:2.8.5'
से http://developer.android.com/guide/topics/resources/providing-resources.html :
कच्ची /
मनमानी फाइलें उनके कच्चे रूप में सहेजने के लिए। एक कच्चे InputStream के साथ इन संसाधनों को खोलने के लिए, संसाधन ID के साथ Resources.openRawResource () पर कॉल करें, जो R.raw.filename है।हालाँकि, यदि आपको मूल फ़ाइल नामों और फ़ाइल पदानुक्रम तक पहुँच की आवश्यकता है, तो आप संपत्ति / निर्देशिका में कुछ संसाधनों को बचाने पर विचार कर सकते हैं (बजाय res / raw /)। संपत्ति में फाइलें / एक संसाधन आईडी नहीं दी जाती हैं, इसलिए आप उन्हें केवल एसेटमैनगर का उपयोग करके पढ़ सकते हैं।
@Mah राज्यों की तरह, Android प्रलेखन ( https://developer.android.com/guide/topics/resources/providing-resources.html ) का कहना है कि json फ़ाइलों को / res (संसाधनों) के तहत / कच्ची निर्देशिका में सहेजा जा सकता है आपके प्रोजेक्ट में निर्देशिका, उदाहरण के लिए:
MyProject/
src/
MyActivity.java
res/
drawable/
graphic.png
layout/
main.xml
info.xml
mipmap/
icon.png
values/
strings.xml
raw/
myjsonfile.json
एक के अंदर Activity, json फ़ाइल को R(संसाधन) वर्ग के माध्यम से एक्सेस किया जा सकता है , और स्ट्रिंग पर पढ़ा जा सकता है:
Context context = this;
Inputstream inputStream = context.getResources().openRawResource(R.raw.myjsonfile);
String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();
यह जावा क्लास का उपयोग करता है Scanner, जिससे एक सरल पाठ / json फ़ाइल को पढ़ने के कुछ अन्य तरीकों की तुलना में कोड की कम लाइनें होती हैं। सीमांकक पैटर्न का \Aअर्थ है 'इनपुट की शुरुआत'। .next()अगले टोकन को पढ़ता है, जो इस मामले में पूरी फाइल है।
परिणामी जौन स्ट्रिंग को पार्स करने के कई तरीके हैं:
optString(String name), optInt(String name)आदि तरीकों, नहीं getString(String name), getInt(String name)तरीकों, क्योंकि optतरीकों में नाकाम रहने के मामले में एक अपवाद के बजाय वापसी अशक्त।import java.util.Scanner; import java.io.InputStream; import android.content.Context;
InputStream is = mContext.getResources().openRawResource(R.raw.json_regions);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String json = new String(buffer, "UTF-8");
का उपयोग करते हुए:
String json_string = readRawResource(R.raw.json)
कार्य:
public String readRawResource(@RawRes int res) {
return readStream(context.getResources().openRawResource(res));
}
private String readStream(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
मिले इस Kotlin टुकड़ा जवाब बहुत मददगार ♥ ️
जबकि JSON स्ट्रिंग प्राप्त करने के लिए पूछे गए मूल प्रश्न, मुझे लगता है कि कुछ को यह उपयोगी लग सकता है। एक छोटा कदम आगे Gsonइस प्रकार के छोटे से कार्य के साथ होता है:
private inline fun <reified T> readRawJson(@RawRes rawResId: Int): T {
resources.openRawResource(rawResId).bufferedReader().use {
return gson.fromJson<T>(it, object: TypeToken<T>() {}.type)
}
}
ध्यान दें कि यदि आप पढ़ते हैं तो आप इसका उपयोग TypeTokenनहीं करना चाहते हैं ।T::classList<YourType>
प्रकार के अनुमान के साथ आप फिर इस तरह का उपयोग कर सकते हैं:
fun pricingData(): List<PricingData> = readRawJson(R.raw.mock_pricing_data)