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.
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 have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.
Hello all I am trying to scan the bottom 6 lines of a text file and display them in a JOptionPane.showMessageDialog currently it is being displayed as [line7, line6, line5, line4, line3, line2] I would prefer it to be displayed as a vertical list instead of the comma seperator.
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = null;
try {
in = new FileInputStream("src/list.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
try {
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 7)
bandWidth.remove(0);
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> reversedSix = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedSix.add(bandWidth.get(i));
JOptionPane.showMessageDialog(null,bandWidth,null,JOptionPane.INFORMATION_MESSAGE);
Try looping the ArrayList and produce a String with new line characters:
String result = "";
for (int i = 0; i < bandWidth.size(); i++)
{
result += bandWidth.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,result ,null,JOptionPane.INFORMATION_MESSAGE);
Note: if this is outputting HTML, then use <br \> instead of \n.
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.