Loading JSON from android assets - android

I have JSON file in assets and I'm trying to read it in my MainActivity method:
private static List<JSONObject> getJSONArray(Context context) {
JSONArray myJSONarr=new JSONArray();
try
{
AssetManager am = context.getAssets();
InputStream is = am.open("chineesecardsdata.json");
String resultJson = is.toString();
is.close();
Log.d("mainActLog","file read ok: "+resultJson);
try {
}
catch (JSONException e)
{
}
}
catch(
IOException e)
{
Log.d("mainActLog","file read fail");
}
}
In log I have:
file read ok:
android.content.res.AssetManager$AssetInputStream#b123fb4

public String loadJSONFromAsset( Context context ) {
String json = null;
try {
InputStream is = context.getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
parse JSON
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray array = new JSONArray(loadJSONFromAsset());
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

why is a JSON file not getting read by my app?

I am new to Stackoverflow and this is my first question.
I am developing an application where I am reading data from a json file from assets folder and storing the values in array list.
here is my code
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(String.valueOf(jsonObject));
}
} catch (JSONException e) {
e.printStackTrace();
}
// Inflate the layout for this fragment
return rootview;
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And this is my json data structure
"root" : {
"child" : [ "data1","data2","data3",.......]},
I want the data1,data2 values inside a list
Try this
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
list.add(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(jsonObject.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}

How to change from Get Json Raw File to Get Json Url?

I have a code that works fine: Get Json from raw file (raw/video_list.json)
public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readRawFile();
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readRawFile() {
String content = "";
Resources resources = getContext().getResources();
InputStream is = null;
try {
is = resources.openRawResource(R.raw.video_list);
byte buffer[] = new byte[is.available()];
is.read(buffer);
content = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
}
Now I want to get Json from Url,I copy Json in the video_list.json file to myjson.com and then get the url (https://api.myjson.com/bins/uyzbl), I change code:
public class VideoListFragment extends BaseListFragment {
VideoAdapter adapter;
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readData("https://api.myjson.com/bins/71535");
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readData(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
No errors occurred in Android Studio but App unfortunately, app has stopped. Can you help me find and fix it?

Can not resolve getAssets() method from inside a java file: Android

I have created a file
inside assests folder and now I want to read the file from a java class and pass it to another function in the same class but for some reason i am unable to use getAssest() method. Please help!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
You should try
getResources().getAssets().open("config.txt")
instead of
context.getAssets().open("config.txt");
Change your Method with Single Parameter Context ....
Pass Context from where you Call this Method..
public void configuration(Context context)
{
String text = "";
try {
InputStream is = context.getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
Yes now as per i think you are not aware from java structure...
Suppose you have this YOUR_CLASS_NAME.java
public void YOUR_CLASS_NAME{
Context context;
YOUR_CLASS_NAME(Context context){
this.context=context;
}
public void configuration(Context context)
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
}
Use this Code
BufferedReader reader = null;
try {
StringBuilder returnString = new StringBuilder();
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
returnString.append(mLine );
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

Append data in Json file

I have this type of JSON:
{
"stampi":
[
{
"nome": "Ovale Piccolo 18.2x13.5cm",
"lunghezza": 18.2,
"larghezza": 13.5,
"altezza": 4,
"volume": 786.83
},
{
"nome": "Ovale Grande 22.5x17.4cm",
"lunghezza": 22.5,
"larghezza": 17.4,
"altezza": 4,
"volume": 1246.54
}
]
}
and normally I read with this code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
and after use the array inside the program.
I have create a menu that add new value inside the JSON file but i have a problem ...this is the code:
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("stampi.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjson_stampi = sb.toString();
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjson_stampi);
// Creating JSONArray from JSONObject
JSONArray objNames = jsonObjMain.names();
System.out.println(objNames.toString());
jsonArray_stampi = jsonObjMain.getJSONArray("stampi");
int num_elem = jsonArray_stampi.length();
jsonObjMain.put( "nome","prova");
jsonObjMain.put( "lunghezza",22);
jsonObjMain.put( "larghezza", 10);
jsonObjMain.put( "altezza", 4);
jsonObjMain.put( "volume", 10.5);
jsonArray_stampi.put( jsonObjMain );
try {
FileWriter file = new FileWriter("c:\\test.json");
//file.write(jsonArray_stampi.);
file.write( JSON.stringify(jsonArray_stampi) );
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} });
why can't work correctly?
the num_elem variable are 2 always..help me!
thx Andrea
You have to create a new JSONObject and then add new data to it and then append to the existing object.
JSONObject jsonObjMain = new JSONObject(myjson_stampi); //Your existing object
JSONObject jO = new JSONObject(); //new Json Object
JSONArray jsonArray_stampi = jsonObjMain.getJSONArray("stampi"); //Array where you wish to append
//Add data
jO.put( "nome","prova");
jO.put( "lunghezza",22);
jO.put( "larghezza", 10);
jO.put( "altezza", 4);
jO.put( "volume", 10.5);
//Append
jsonArray_stampi.put(jO);
Also you should write back the complete jsonObject back to the file.
file.write(JSON.stringify(jsonObjMain));
Looks like you're trying to write to a file called c:\\test.json. Try using the proper Android way to write to files with openFileOutput. Examples are here.
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

How to insert one more item in a json existing structure with gson?

The code below generates correctly the first structure of the json file.
gson = new GsonBuilder().setPrettyPrinting().create();
AudDetHeader AudDetHeader = new AudDetHeader();
//ArrayList<OrderDetail> AudDetList = new ArrayList<OrderDetail>();
Map<String, AudDet> AudDetList = new HashMap<String, AudDet>();
AudDet AudDet = new AudDet();
AudDet.setLineId("1");
AudDet.setItemNumber("ABC");
AudDet.setQuantity(9);
AudDet.setPrice(10.00);
List<String> phones = new ArrayList<String>();
phones.add("24530001");
phones.add("24530002");
phones.add("24530003");
AudDet.setPhones(phones);
AudDetList.put("teste 2", AudDet);
AudDetHeader.setAudDetList(AudDetList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(AudDetHeader);
BufferedWriter bufferedWriter = null;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
The result of the code:
{
"Results": {
"teste 2": {
"itemNumber": "ABC",
"lineId": "1",
"phones": [
"24530001",
"24530002",
"24530003"
],
"price": 10.0,
"quantity": 9
}
}
}
I want to add a new item. My desire is to stay as the structure below.
{
"Results":{
"teste 2":{
"itemNumber":"ABC",
"lineId":"1",
"phones":[
"24530001",
"24530002",
"24530003"
],
"price":10.0,
"quantity":9
},
"teste 3":{
"itemNumber":"DEF",
"lineId":"2",
"phones":[
"30303030",
"40404040",
"505050"
],
"price":11.0,
"quantity":12
}
}
}
The AudDetHeader.class
public class AuditoriaDetalheHeader {
#SerializedName("Results")
private Map<String, AuditoriaDetalhe> AuditoriaDetalheList;
...
}
The AudDet.class
public class AuditoriaDetalhe {
String lineId = null;
String itemNumber = null;
int quantity = 0;
Double price = null;
List<String> phones = new ArrayList<String>();
...
}
Worked for me with this code!!!
Main class
private static File fileJson = new File(Environment.getExternalStorageDirectory() + "/download/test/test.json");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teste_criajson);
createJsonStructure();
Button btnSave = (Button)findViewById(R.id.btSave);
btnSalvar.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
try {
String strFileJson = getStringFromFile(fileJson.toString());
JSONObject jsonObj = new JSONObject(strFileJson);
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
String idAud = "10";
AudDet ad = new AudDet();
ad.setLineId("2");
ad.setItemNumber("DEF");
ad.setQuantity(22);
ad.setPrice(22.22);
List<String> phones = new ArrayList<String>();
phones.add("22");
phones.add("22");
phones.add("22");
ad.setPhones(phones);
String jsonStr = jsonParser.parse(gson.toJson(ad)).toString();
JSONObject JSONObject = new JSONObject(jsonStr);
jsonObj.getJSONObject("Results").put(idAud, JSONObject);
writeJsonFile(fileJson, jsonObj.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
If do not exists json file, then i create with basic structure for insert the itens.
public static void createJsonStructure(){
if(!fileJson.exists()){
try {
fileJson.createNewFile();
String jsonString = "{\"Results\":{}}";
writeJsonFile(fileJson, jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Open the json file to get the string format, and prepare to insert a new item:
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
Writes into the json file that already exists:
public static void writeJsonFile(File file, String json)
{
BufferedWriter bufferedWriter = null;
try {
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(json);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Categories

Resources