I'm working on JSON. I wrote code which can to parse JSON and show listview(images and text).
Now I want to save my JSON in file (json.txt).
This is a my code. I try to save JSON but when I debug it on my json.txt file saved only first data, but I have 20 data in JSON
if anyone know solution please help .......
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
yourFile = new File("/sdcard/json.txt");
try {
writer = new OutputStreamWriter(
new FileOutputStream(yourFile), "UTF-8");
writer.write(jsonobject.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
open your file in append mode.
new OutputStreamWriter(new FileOutputStream(yourFile,true), "UTF-8");
Use a separate variable for the JSONObject retrieved from the URL, and the one used to loop the data array:
jsonparser = new JSONParser();
JSONObject jsonfromurl = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonfromurl.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
yourFile = new File("/sdcard/json.txt");
try {
writer = new OutputStreamWriter(
new FileOutputStream(yourFile), "UTF-8");
writer.write(jsonfromurl.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should follow the same style as here. From what I can see, they actually write bytes to the FileOutputStream, whereas you try to write a string. FileOutputStream only accepts bytes, as per the documentation.
Try writer.write(jsonobject.toString().getBytes()); instead.
Related
Currently I am working with a project where I need to get some data from remote server as JSON then need to extract array. Here I am getting data successfully, But problems are near while loop.
I am getting data from remote server successfully.
For example my remote url giving output as:
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},
{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}`
Code
try {
ur = "http://localhost/getsample.php";
URL url = new URL(ur);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line !=null){
line = bufferedReader.readLine();
data = data+line;
}
data = data.replace("null", "");
JSONArray JA = new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO = (JSONObject) JA.get(i);
idArray = idArray + JO.get("id") + ",";
amountArray = amountArray + JO.get("amount") + ",";
course_codeArray = course_codeArray + JO.get("course_code") + ",";
courseArray = courseArray + JO.get("course") + ",";
contentArray = contentArray + JO.get("content") + ",";
thumbArray = thumbArray + JO.get("thumb") + ",";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
The data you get from the server are at JSON format but they are not Array . this is an object ,
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}
So you have to loop inside the json object like
for (var key in jsonResponse) {
if (jsonResponse.hasOwnProperty(key)) {
console.log(key + " -> " + jsonResponse[key]);
}
}
EDIT : If you have multiple Objects inside an object you have to loop inside them ( external for) like for(var i in JsonObject)
Your Code is should be like According to your current Response
try{
JSONObject jso = new JSONObject(data);
amountArray =jsonObject.getString("amount");
course_codeArray =jsonObject.getString("yourNextKey");
courseArray = jsonObject.getString("yourNextKey");
contentArray = jsonObject.getString("yourNextKey");
thumbArray = jsonObject.getString("yourNextKey");
}
catch (JSONException e) {
e.printStackTrace();
}
I parsed this data from Wikipedia and trying to get only characters from here. But the result comes with \n* in the front of data.
"": "=== 고양이의 종류 ===\n [[시암고양이]]\n* [[페르시안 네브스카야]]\n* [[페르시안]]\n*
[[노르웨이지언 포레스트]]\n* [[터키시 앙고라]]\n* [[아메리칸 숏헤어]]\n* [[브리티시 숏헤어]]\n*
[[러시안블루]]\n* [[뱅갈]]\n* [[메인쿤]]\n* [[랙돌]]\n* [[히말라얀]]\n* [[재패니즈
밥테일]]\n* [[오리엔탈 숏헤어]]\n* [[피터볼드]]\n* [[스코티시 폴드]]\n* 스코티시 스트레이트\n*
[[하일랜드 폴드]]\n* [[시베리안 포레스트]]\n* [[터키시 반]]\n* [[코리안 쇼트헤어]]\n*
[[올블랙]]\n* [[사바나캣]]\n* [[쿠나]]\n* [[아비시니안]]\n* 먼치킨"
This is my code.
try {
URL url = new URL("https://ko.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=20&titles=%EA%B3%A0%EC%96%91%EC%9D%B4&format=json");
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
while(true){
String data = reader.readLine();
if(data == null) break;
result += data;
}
JSONObject obj = new JSONObject(result);
JSONObject query = (JSONObject) obj.get("query");
JSONObject pages = (JSONObject) query.get("pages");
JSONObject pageid = (JSONObject) pages.get("93349");
JSONArray revisions = (JSONArray) pageid.get("revisions");
String catcat = String.valueOf(revisions);
String star = "\n*";
catcat = catcat.replaceAll("\\[\\[","").replaceAll("\\]\\]",",").replaceAll("\\r|\\n", "").replaceAll(star,"");
String[] catcategory = catcat.split(",");
for (int i = 0; i<catcategory.length;i++){
list.add(catcategory[i]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Result for this looks like
\n시암고양이
\n페르시안
and I want to remove \n*.
How to split parsed String data without special characters?
Try this piece of code, It's removed \n* , Then you can add _result_word to your list.
for (int i = 0; i < catcategory.length; i++) {
try {
String _result_word = catcategory[i].replaceFirst("\\\\n", "").replace("*", "");
//String _result_word=catcategory[i].replaceFirst("\\\\n", "").replace("*", "").replaceFirst("\\\\n", "").replace("*", "");
System.out.println("" + _result_word);
list.add(_result_word);
} catch (Exception ex) {
System.out.println("Special Exception occurred at index : i = " + i);
ex.printStackTrace();
}
}
Everything correct except one line where you need escape asterisk character and escape slash character
String star = "\\\\n\\*";
str.replaceAll(star, "");
I'm trying to randomize JSON array this way:
private static JSONArray getJSONArray(Context context) {
JSONArray myJSONarr=new JSONArray();
JSONArray myRandomizedJSONarr=new JSONArray();
try
{
InputStream is = context.getAssets().open("chineesecardsdata.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String resultJson = new String(buffer, "UTF-8");
try {
JSONObject myJSONObject=new JSONObject(resultJson);
myJSONarr=myJSONObject.getJSONArray("data");
Log.d("mainActLog","Array before random: "+myJSONarr.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
}
catch(
IOException e) {
}
try {
ArrayList<Integer> intArr1 = new ArrayList<>(myJSONarr.length());
for (int i = 0; i < myJSONarr.length(); i++) {
intArr1.add(i);
}
Collections.shuffle(intArr1);
for (int i = 0; i < intArr1.size(); i++) {
myRandomizedJSONarr.put(i, myJSONarr.getJSONObject(intArr1.get(i)));
if (i == (myJSONarr.length() - 1))
break;
}
Log.d("mainActLog","Array after random: "+myRandomizedJSONarr.toString());
}
catch (JSONException e){}
return myRandomizedJSONarr;
}
As a result of this not only JSON objects are randomizing, but also keys and values.
I mean, I had an array like this:
[
{"id":"0","hieroglyph":"水","pinyin":"Shuǐ","pinyin_num":"Shui3","russian":["вода"],"hsk":"1"},
{"id":"1","hieroglyph":"人","pinyin":"Rén","pinyin_num":"Re2n","russian":["человек"],"hsk":"1"},
{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"},
{"id":"3","hieroglyph":"不","pinyin":"Bù","pinyin_num":"Bu4","russian":["нет"],"hsk":"1"},
{"id":"4","hieroglyph":"少","pinyin":"Shǎo","pinyin_num":"Sha3o","russian":["мало"],"hsk":"1"}]
And after randomize it looks like this
[{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"},
{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"},
{"id":"4","hieroglyph":"少","pinyin":"Shǎo","pinyin_num":"Sha3o","russian":["мало"],"hsk":"1"},
{"id":"3","hieroglyph":"不","pinyin":"Bù","pinyin_num":"Bu4","russian":["нет"],"hsk":"1"},
{"id":"2","hieroglyph":"日","pinyin":"Rì","pinyin_num":"Ri4","russian":["день"],"hsk":"1"}]
Why not just shuffle the array directly?
List<JSONObject> myList = new ArrayList<JSONObject>();
for(int i = 0; i < myJSONarr; i++){
myList.add(myJSONarr.getJSONObject(i));
}
Collections.shuffle(myList);
I am working on an Android project. I am creating a graph and populating the graph with json content. My problem is that i keep getting this error and i am not sure why. java.lang.NegativeArraySizeException: -2
My Log.v shows the content of the array. So it's not empty. Maybe i am missing something.
I go through the rest api and add everything to the arraylist resModelList.
In the onPostExecute, I want to add my y-axis values to this array list yVals1.
This is where i get my error. (java.lang.NegativeArraySizeException: -2)
If i add the values like this, I get no error.
yVals1 = new ArrayList<Entry>();
yVals1.add(new Entry(1451606400, 10));
yVals1.add(new Entry(1454284800, 20));
yVals1.add(new Entry(1456790400, 30));
yVals1.add(new Entry(1459468800, 50));
My code
Global variables
ArrayList<ResultModel> resModelList;
ArrayList<Entry> yVals1;
Parse Json
//getResult
public class JSONTask extends AsyncTask<String, String, List<ResultModel>> {
#Override
protected List<ResultModel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie",session_name+"="+session_id);
connection.setRequestProperty("X-CSRF-Token", token);
//connection.setRequestProperty("Accept-Encoding", "identity");
connection.connect();
int length = connection.getContentLength();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null){
buffer.append(line);
}
Log.v("TESt", " " + length);
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
resModelList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
ResultModel resModel = new ResultModel();
resModel.setPost_date(finalObject.getString("post_date"));
resModel.setHow_much_has_ocd(finalObject.getString("how_much_has_ocd"));
resModelList.add(resModel);
}
return resModelList;
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ResultModel> result) {
super.onPostExecute(result);
if(!resModelList.isEmpty()){
//here is where i get my errors
yVals1 = new ArrayList<Entry>();
for (ResultModel ocd : resModelList){
int score = Integer.parseInt(ocd.getHow_much_has_ocd());
int timeStamp = Integer.parseInt(ocd.getPost_date());
//I get these log values
Log.v("Score: ", " " + score + " Timestamp: " + timeStamp);
yVals1.add(new Entry(timeStamp, score));
}
graph();
Log.v("Not Empty list", "");
}else {
Log.v("Empty list", "");
}
}
}
finalJson log.v
[{"post_date":"1481895820","did_you_avoid":"25","how_much_has_ocd":"81","how_would_you_rate":"82","overall_how_would":"35","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481723564","did_you_avoid":"13","how_much_has_ocd":"10","how_would_you_rate":"13","overall_how_would":"16","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481723488","did_you_avoid":"28","how_much_has_ocd":"56","how_would_you_rate":"75","overall_how_would":"32","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481537274","did_you_avoid":"53","how_much_has_ocd":"59","how_would_you_rate":"15","overall_how_would":"71","were_there_any_distressing":"1","uid":"2"},{"post_date":"1481295470","did_you_avoid":"67","how_much_has_ocd":"64","how_would_you_rate":"66","overall_how_would":"57","were_there_any_distressing":"0","uid":"2"},{"post_date":"1481097609","did_you_avoid":"72","how_much_has_ocd":"85","how_would_you_rate":"62","overall_how_would":"64","were_there_any_distressing":"0","uid":"2"},{"post_date":"1480673252","did_you_avoid":"33","how_much_has_ocd":"69","how_would_you_rate":"84","overall_how_would":"37","were_there_any_distressing":"1","uid":"2"},
I am a beginner so it might just be simple mistake.
Thanks in advance
I found the error. It was my graph library.
I am using MPAndroidChart library and you need to sort the data. My back-end was sorted desc. I had to change it to Post date (asc).
Its related to this problem.
NegativeArraySizeException adding Scatter Data to a CombinedChart
I hope this helps someone else.
I want to read many jsonArrays from a file.
these are the JsonArrays in the file:
[{name:"John",preis:"123",bild:1235},
{name:"Smith",preis:"256",bild:7205},
{name:"Steeven",preis:"632",bild:324035}]
[{name:"Hans",preis:"85",bild:1005},
{name:"Peter",preis:"420",bild:22205},
{name:"Joe",preis:"200",bild:3240}]
[{name:"Jane",preis:"355",bild:10505},
{name:"Calith",preis:"630",bild:96505},
{name:"Eva",preis:"260",bild:32440}]
I can not read the whole file, but i can read only the first jsonArray from the file.
here is my code to read it:
ArrayList<Werkzeug> myWerkzeuge = new ArrayList<Werkzeug>();
String alteBestellung = "";
try {
FileInputStream fileInputStream = openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ( (line = bufferedReader.readLine()) != null){
alteBestellung = alteBestellung + line;
}
JSONArray jsonArray = new JSONArray(alteBestellung);
for (int i = 0; i<jsonArray.length(); ++i){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name_werkzeuge = (String) jsonObject.get("name");
String preis_werkzeuge = (String) jsonObject.get("preis");
Integer bild_werkzeuge = Integer.valueOf( (String)jsonObject.get("bild") );
myWerkzeuge.add( new Werkzeug(name_werkzeuge, preis_werkzeuge, bild_werkzeuge));
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
String bestellung = " ";
for (int i = 0; i< myWerkzeuge.size(); ++i) {
bestellung = bestellung + "\n" + myWerkzeuge.get(i).getName() + " " + myWerkzeuge.get(i).getPreis() + " €" + myWerkzeuge.get(i).getBild();
}
bestellungsTextView.setText( bestellung );
How to read these three jsonArrays from this file?
What you need is a valid json.
You probably want a JsonArray of JsonArray :
[
[{name:"John",preis:"123",bild:1235},
{name:"Smith",preis:"256",bild:7205},
{name:"Steeven",preis:"632",bild:324035}],
[{name:"Hans",preis:"85",bild:1005},
{name:"Peter",preis:"420",bild:22205},
{name:"Joe",preis:"200",bild:3240}],
[{name:"Jane",preis:"355",bild:10505},
{name:"Calith",preis:"630",bild:96505},
{name:"Eva",preis:"260",bild:32440}]
]
This is not valid json .
First of all make a valid json.