Create JSON Object from Local JSON File - android

How do I create a "JSONObject" from a local JSON file inside my "raw" folder.
I have the following JSON file under the "raw" folder of my android app project. The file is called "app_currencies.json". I need the information contained on this file as an object in my class. Below are the file contents:
{
"EUR": { "currencyname":"Euro", "symbol":"EUR=X", "asset":"_European Union.png"},
"HTG": { "currencyname":"Haitian Gourde", "symbol":"HTG=X", "asset":"ht.png"},
"WST": { "currencyname":"Samoan Tala", "symbol":"WST=X", "asset":"ws.png"},
"GBP": { "currencyname":"British Pound", "symbol":"GBP=X", "asset":"gb.png"}
}
I think what I need is to use the following:
//Get data from Json file and make it available through a JSONObject
InputStream inputStream = getResources().openRawResource(R.raw.app_currencies.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JSONObject jObject = new JSONObject;
jObject is what I need. I think I need an InputStream, ByteArrayOutputStream so that I can store it into JSONObject... the problem is that I'm not sure how to implement this code properly so that I can access the data? If any of you could give detailed instructions on how to do this, I would really appreciate it.

The following code reads a json file into a Json Array. See if it helps. Note, the file is stored in Assets instead
BufferedReader reader = null;
try {
// open and read the file into a StringBuilder
InputStream in =mContext.getAssets().open(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
// line breaks are omitted and irrelevant
jsonString.append(line);
}
// parse the JSON using JSONTokener
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();
// do something here if needed from JSONObjects
for (int i = 0; i < array.length(); i++) {
}
} catch (FileNotFoundException e) {
// we will ignore this one, since it happens when we start fresh
} finally {
if (reader != null)
reader.close();
}

Related

How to create a properly formatted array of gson objects

Everytime someone makes a transaction in my app I would like to save it to local storage using json / gson. I believe I am nearly there but my problem is correctly formatting the json file every time I write to it.
I would like to append to the file every time I create a Transaction object, and then at some point read every Transaction object from the file for display in a list. Here is what I have so far:
public void saveTransaction(Transaction transaction)
throws JSONException, IOException {
Gson gson = new Gson();
String json = gson.toJson(transaction);
//Write the file to disk
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND);
writer = new OutputStreamWriter(out);
writer.write(json);
} finally {
if (writer != null)
writer.close();
}
}
My transaction object has an amount, a user id and a boolean, writing with this code I can read the following json String:
{"mAmount":"12.34","mIsAdd":"true","mUID":"76163164"}
{"mAmount":"56.78","mIsAdd":"true","mUID":"76163164"}
I am reading these values like so but can only read the first one (I guess because they are not in an array / properly formatted json object):
public ArrayList<Transaction> loadTransactions() throws IOException, JSONException {
ArrayList<Transaction> allTransactions = new ArrayList<Transaction>();
BufferedReader reader = null;
try {
//Open and read the file into a string builder
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//Line breaks are omitted and irrelevant
jsonString.append(line);
}
//Extract every Transaction from the jsonString here -----
} catch (FileNotFoundException e) {
//Ignore this one, happens when launching for the first time
} finally {
if (reader != null)
reader.close();
}
return allTransactions;
}
im not sure i understand your question, but have you tried creating a TransactionCollection object that has an ArrayList<Transaction> transactions
and create your json from the TransactionCollection object instead of each transaction?

Reading CSV file in resources folder android

I am developing an android app in netbeans. I am trying to read CSV file using opencsv. When I put the file in resources folder and try to read it from there, there's an error while building saying invalid resource directory. Where should I store csv file so that it can be read each time the app starts?
you should put csv file in assets folder ..
InputStreamReader is = new InputStreamReader(getAssets()
.open("filename.csv"));
BufferedReader reader = new BufferedReader(is);
reader.readLine();
String line;
while ((line = reader.readLine()) != null) {
}
Some advices;
Create an object for holding one row data into the csv. ( Ex: YourSimpleObject . It provides you to manage the data easily.)
Read file row by row and assign to object. Add the object to list. (Ex: ArrayList<YourSimpleObject >)
Code:
private void readAndInsert() throws UnsupportedEncodingException {
ArrayList<YourSimpleObject > objList= new ArrayList<YourSimpleObject >();
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("questions/question_bank.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
StringTokenizer st = null;
try {
while ((line = reader.readLine()) != null) {
st = new StringTokenizer(line, ",");
YourSimpleObject obj= new YourSimpleObject ();
//your attributes
obj.setX(st.nextToken());
obj.setY(st.nextToken());
obj.setZ(st.nextToken());
obj.setW(st.nextToken());
objList.add(sQuestion);
}
} catch (IOException e) {
e.printStackTrace();
}
}
As an alternative, take a look at uniVocityParsers. It provides a vast number of ways to parse delimited files. The example bellow loads a Csv File (see in the picture below) from a res/raw folder into a InputStream object, and read it in a colunar manner (a map where key=Column & value=ColumnValues).
calendario_bolsa.csv
//Gets your csv file from res/raw dir and load into a InputStream.
InputStream csvInputStream = getResources().openRawResource(R.raw.calendario_bolsa);
//Instantiate a new ColumnProcessor
ColumnProcessor columnProcessor = new ColumnProcessor();
//Define a class that hold the file configuration
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setProcessor(columnProcessor);
//Creates a new CsvParser, passing the settings into its construtor:
CsvParser csvParser = new CsvParser(parserSettings);
//Calls parse method, instantiating an InputStreamReader, passing to its constructor the InputStream object
csvParser.parse(new InputStreamReader(csvInputStream));
//Gets the csv data as a Map of Column / column values.
Map<String, List<String>> columnarCsv = columnProcessor.getColumnValuesAsMapOfNames();
To add univocityParsers into your Android Project:
compile group: 'com.univocity', name: 'univocity-parsers', version: '2.3.0'
Using opencsv:
InputStream is = context.getAssets().open(path);
InputStreamReader reader = new InputStreamReader(is, Charset.forName("UTF-8"));
List<String[]> csv = new CSVReader(reader).readAll();
you may use this code
try {
InputStream csvStream = assetManager.open(CSV_PATH);
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvReader = new CSVReader(csvStreamReader);
String[] line;
// throw away the header
csvReader.readNext();
while ((line = csvReader.readNext()) != null) {
questionList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
you may download csvreader file from
http://sourceforge.net/projects/opencsv/files/latest/download
and import in your project

android Json parser offline

I'm new to the android world and i have some problem.
I'm developing a project under android and it require a json parser. I get my json file from a web service developed under Zend framework, the link to the web service : "manganew:8080/wsmanganew/manga/manga/idmanga/1" and the content of the json file is
{
"manga": [
{
"idmanga":"1",
"titre":"naruto",
"episode":"145",
"url":"http:\/\/naruto.com\/",
"image":null,
"description":"Naruto Shippuuden .",
"tv":"TV Tokyo",
"dtdebut":"2013-05-23 12:30:00",
"iduser":"1"
}
]}
I'm following this tutorial "http://www.androidhive.info/2012/01/android-json-parsing-tutorial/".
i don't know how index to the web service link in the android, any help will be useful.
thank you
so, what do you need to do? download json object from that url into your app?
that code has method getJSONFromUrl in it's class, you should use it
though, according to comments it has flaws in it.
to read string from file use this code
BufferedReader reader = new BufferedReader(new FileReader("/mnt/sdcard/docs/file.json"));
String line, results = "";
while( (line = reader.readLine()) != null)
results += line;
reader.close();
JSONObject obj = new JSONObject(results);
replace path with path to your file
try this
BufferedReader reader = new BufferedReader(new FileReader("C:\\file.json"));
String line, results = "";
while( (line = reader.readLine()) != null)
results += line;
reader.close();
JSONObject obj = new JSONObject(results);
Replace with your local machine download field path C:\\file.json

JSON Parsing without using URL to read json file in android

I am using url to take the file for parsing. Now i want read the file which is in sdcard for parsing.How can i do this?
here my code
reading file from url
private static String url = "http://10.0.2.2/device1.json";
JSONObject json = jParser.getJSONFromUrl(url);
devices = json.getJSONArray(TAG_DEVICES);
now i want do this from reading the file in sdcard
java.io.File device = new java.io.File("/mnt/sdcard/device1.json");
FileReader device_Fr = new FileReader(device);
next how to pass this file for parsing?
Use this code
read data from file into string & pass that to JSONObject.
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line, results = "";
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
JSONObject obj = new JSONObject(results);
One way to do it is to read the json and store it in a string. Then parse it like this:
String jsonStr = // read from file
JSONObject json = new JSONObject( jsonStr);
// parse
 
  devices = json.getJSONArray(TAG_DEVICES);

Android parse json from url and store it

Hi there i'm creating my first android app and i'm wanting to know what is the best and most efficient way of parsing a JSON Feed from a URL.Also Ideally i want to store it somewhere so i can keep going back to it in different parts of the app. I have looked everywhere and found lots of different ways of doing it and i'm not sure which to go for. In your opinion whats the best way of parsing json efficiently and easily?
I'd side with whatsthebeef on this one, grab the data and then serialize to disk.
The code below shows the first stage, grabbing and parsing your JSON into a JSON Object and saving to disk
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
// Save the JSONOvject
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( jsonObject );
out.close();
Once you have the JSONObject serialized and save to disk, you can load it back in any time using:
// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
JSONObject jsonObject = (JSONObject) in.readObject();
in.close();
Your best bet is probably GSON
It's simple, very fast, easy to serialize and deserialize between json objects and POJO, customizable, although generally it's not necessary and it is set to appear in the ADK soon. In the meantime you can just import it into your app. There are other libraries out there but this is almost certainly the best place to start for someone new to android and json processing and for that matter just about everyone else.
If you want to persist you data so you don't have to download it every time you need it, you can deserialize your json into a java object (using GSON) and use ORMLite to simply push your objects into a sqlite database. Alternatively you can save your json objects to a file (perhaps in the cache directory)and then use GSON as the ORM.
This is pretty straightforward example using a listview to display the data. I use very similar code to display data but I have a custom adapter. If you are just using text and data it would work fine. If you want something more robust you can use lazy loader/image manager for images.
Since an http request is time consuming, using an async task will be the best idea. Otherwise the main thread may throw errors. The class shown below can do the download asynchronously
private class jsonLoad extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
// Instantiate a JSON object from the request response
try {
JSONObject jsonObject = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");
try {
file.createNewFile();
FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
writer.write(result);
writer.flush();
writer.close();
}
catch (IOException e) { e.printStackTrace(); return false; }
}
}
Unlike the other answer, here the downloaded json string itself is saved in file. So Serialization is not necessary
Now loading the json from url can be done by calling
jsonLoad jtask=new jsonLoad ();
jtask.doInBackground("http:www.json.com/urJsonFile.json");
this will save the contents to the file.
To open the saved json string
File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//print log
}
JSONObject jsonObject = new JSONObject(text);

Categories

Resources