I have this code :
StringBuffer sb = new StringBuffer();
try {
BufferedReader reader = request.getReader();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
the line :
System.out.println(line);
prints in console at the end of the loop like this:
{"signupname":"John","signuppassword":"1234","signupnickname":"Jonny",
"signupdescription":"student","signupphoto":"(here photo url)"}
how can I get only the values of the keys? I want something like this:
John
1234
Jonny
student
(here photo url)
Thanks for helpers:)
If each row is a complete JSON object. You can use Gson JSON parser.
https://mvnrepository.com/artifact/com.google.code.gson/gson
StringBuffer sb = new StringBuffer();
try {
BufferedReader reader = request.getReader();
String line;
Gson gson = new Gson();
while ((line = reader.readLine()) != null) {
Map map = gson.fromJson(line, Map.class);
for(Object value : map.values()) {
System.out.println(value);
}
sb.append(line);
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
The format looks like JSON. If that's true, use any JSON parser you like and get only the keys.
E.g. org.json:json in Maven Central.
https://github.com/stleary/JSON-java
Related
I have created a JSONObject and put values in it like below .
Then I converted my object "h" to string and write a file in the sdcard with that string.
JSONObject h = new JSONObject();
try {
h.put("NAme","Yasin Arefin");
h.put("Profession","Student");
} catch (JSONException e) {
e.printStackTrace();
}
String k =h.toString();
writeToFile(k);
In the file I see text written like the format below .
{"NAme":Yasin Arefin","Profession":"Student"}
My question is how do I read that particular file and convert those text back to JSONObject ?
To read a file you have 2 options :
Read with a BufferReader and your code would look like this :
//Path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
//Load the file
File file = new File(sdcard,"file.json");
//Read text from file
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) {
//You'll need to add proper error handling here
}
The option 2 would be to use a library such as Okio:
In your Gradle file add the library
implementation 'com.squareup.okio:okio:2.2.0'
Then in your activity:
StringBuilder text = new StringBuilder();
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
for (String line; (line = source.readUtf8Line()) != null; ) {
text.append(line);
text.append('\n');
}
}
I want to implement my old code when I was populating JSON array into listview but my current json haven't specified array, overall json is an array...
Can somebody tell me how to transform my code to use JSON like this?
https://api-v2.hearthis.at/categories/drumandbass/?page=15&count=2
Code to use gson, my old:
protected List<Model> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");
List<Model> dataModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Model modelList = gson.fromJson(finalObject.toString(), Model.class);
dataModelList.add(modelList);
}
return dataModelList;
} 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;
}
Instead of doing this:
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = new JSONArray("arrayname");
Just do this:
JSONArray parentArray = new JSONArray(finalJson);
If i understand the problem correctly, i guess you are having trouble parsing the array who's name is not specified with a key. So, a simple but not a very good way of doing this would be, when you create your finalJson like this:
String finalJson = buffer.toString();
just add a line to check if it contains an array opening bracket, like this:
if(finalJson.contains("[")){
finalJson = finalJson.replace("[","{
"arrayname": [");
}
also, close the array appropriately.
if(finalJson.contains("]")){
finalJson = finalJson.replace("]","]
}");
}
This way, u will have a name for the array to parse, and i guess this is what you are looking for. But this approach might fail if you have more than 1 array in your Json, in that case you will have to use startsWith & endsWith string methods to give a name to your array. But, as of now, from what your Json looks like, this would work.
I am using the following code to get data from a file
try {
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput(TEXTFILE));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String string;
StringBuilder stringbuilder = new StringBuilder();
while ((string=bufferedReader.readLine())!=null){
stringbuilder.append(string);
}
EditText.setText(stringbuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
It works but
when I put the string=bufferedReader.readLine() before While, I get an exception : java.lang.OutOfMemoryError
You're reading a line from the BufferedReader, and storing the result in string. After that, you check if string != null, and if not, you append string to stringbuilder. You're repeating this until string == null.
The confusion here might be the comparison of an assignment statement:
while ((string = bufferedReader.readLine()) != null) { ... }
This is a short notation of the following:
string = bufferedReader.readLine();
while (string != null) {
...
string = bufferedReader.readLine();
}
I have this simple bit of code causing me a headache
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("Quiz.csv")));
List<String> lines = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
catch (Exception e)
{
Log.e(getLocalClassName(), e.toString());
}
I get a nullPointerException from logcat when I hit the while loop
Your lines is null. Initialise it:
List<String> lines = new ArrayList<String>();
You have to initialize lines like so:
List<String> lines = new ArrayList<String>();
I'm using the following code to handle REST responses from my server:
if (response.getEntity() != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
try {
rr.jsonObject = new JSONObject(tokener);
} catch (JSONException e) {
e.printStackTrace();
Log.d("parsing", "creating json array");
try {
rr.jsonArray = new JSONArray(tokener);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
If the response is an JSONObject, it works perfectly but if the server returns a JSONArray, the second try block also throws although it's correct json.
03-30 14:09:15.069: W/System.err(6713): org.json.JSONException: End of input at character 314 of [{"__className":"stdClass","char3code":"DEU","fips_name":"Germany","alternate_names":"Germany, Deutschland, Allemagne, Alemania"},{"__className":"stdClass","char3code":"USA","fips_name":"United States","alternate_names":"United States of America, Vereinigte Staaten von Amerika, \u00c9tats-Unis, Estados Unidos"}]
I expect the reason that this is failing is that when you call new JSONArray(tokener) the tokener is no longer positioned at the start of the token stream. Try creating a new JSONTokener instance for the 2nd attempt at parsing..