having some serious problem when trying to read a local JSON file. I've looked everywhere for many days now and the best and farthest I could get was copying from Faizan's answer.
Reading a json file in Android
How come that Android Studio doesn't let me generate the second try-catch code block here?
Help and advice are very much appreciated!!
This is My code
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("names.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;
}
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
How come that Android Studio doesn't let me generate the second
try-catch code block here?
Simply, because your code is not inside a method.
Doing something like below should solve the error.
public void someMethodIdentifier(){ // doesn't have to be void return type, you know better than me what type you want to return.
String jsonString = loadJSONFromAsset();
try {
JSONObject json = new JSONObject(jsonString);
JSONObject jObject = json.getJSONObject("female");
JSONObject jObject2 = jObject.getJSONObject("adult");
String name = jObject2.toString();
}
catch (Exception e) {
e.printStackTrace();
}
}
Note - from the looks of the statements that's contained within the try block I think you intended to return some data? if that's the case just replace the void return type with the appropriate return type and return that data.
Related
Im currently building a GSONFileWriter class.
public class GSONFileWriter {
private File jsonFile;
private final String json;
public GSONFileWriter(String json) {
this.json = json;
}
public void generateJsonFileIfNotExists(String pathname) {
try {
jsonFile = new File(pathname);
if (!jsonFile.exists()) {
if (jsonFile.createNewFile()) {
System.out.println("File successful created.");
} else {
System.out.println("Error: Building the file went wrong!");
System.exit(1);
}
}
fillJsonFile();
} catch (Exception e) {
System.err.println("Error: Building the file went wrong!");
}
}
private void fillJsonFile() {
try (PrintWriter writer = new PrintWriter(jsonFile, StandardCharsets.UTF_8)) {
writer.append(json);
writer.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
it is called inside my CLI class
Gson gson = new Gson();
String json = gson.toJson(target);
GSONFileWriter gsonFileWriter = new GSONFileWriter(json);
gsonFileWriter.generateJsonFileIfNotExists("EmployeeData.json");
It creates and builds a new JSON File with an object inside it.
{"salary":34000.0,"name":"Hans","age":30,"id":"d40507a7-a802-4494-9a0c-5a97a0a4d0bf"}
However the Problem is, that whenever i run the code again, the old file gets overwritten and a new one created. I tried to change the code, so that it adds a new object to the file, instead of overwrite it. Any tips?
I would recommend:
At first: Read your json file as String if it exists.
String file = "<File>";
String json = new String(Files.readAllBytes(Paths.get(file)));
Second you transform this string into a JsonObject using JsonParser:
JsonObject object = JsonParser.parseString(json).getAsJsonObject();
now you obtained your json-file as JsonObject tree and can manipulate this as you like. Using:
JsonObject.get(<MemberName>);
JsonObject.add(String <propertyName>, JsonElement <value>);
JsonObject.addProperty(String <propertyName>, Number/String/Boolean/Char <value>);
, etc.
Whenever you are finished you can write this to your json-file, either through a OutputStream or whatever you like.
I am using below JSON format:
[{object1},{object2},{object3}...]
I am reading a JSON file object wise means one by one (object by object) and my below code working fine.
I want to read it in chunks(at a time 10 objects). I have tried a lot but I am not getting any solution (without using Spring Batch). Can anybody please help me how to read in chunks
#Component
public class PdpiRunner3 implements CommandLineRunner {
#Override
public void run(String... args) throws Exception {
try {
JsonReader jsonReader = new JsonReader(new InputStreamReader(new ClassPathResource("/json/trades2.json").getInputStream(),StandardCharsets.UTF_8));
Gson gson = new GsonBuilder().create();
jsonReader.beginArray();
while (jsonReader.hasNext()) { // next json array element
PDPIfiles json = gson.fromJson(jsonReader, PDPIfiles.class);
if (json != null) {
System.out.println(json);
}
}
jsonReader.endArray();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is it possible to read json element In Chunk without spring Batch pleas help ?
I am reading some data via BLE from my peripheral device to my android app.
the app gets the data from BLE device in a JSON format. it all works fine, except in few cases when i get incomplete JSON string from BLE device (i have no control over that and i need to handle whatever i receive. Initially, i was getting a simple JSON array like
[wifi1, wifi2, wifi3, wifi4, wifi5]
So if get incomplete string i will handle JSON parse exception and use String Tokenizer and simply parse each token and get the wifi name
StringTokenizer tokens = new StringTokenizer(new String(bytes), ",");
int size = tokens.countTokens();
HashMap<String, Object> map;
for (int i = 0; i < size; i++) {
map = new HashMap<String, String>();
map.put("Wifi, tokens.nextToken().replace("\"", "").replace("]", "").replace("[", ""));
But now the JSON string has been changed and includes a lot of other information, this is the new JSON that i get
[{"ssid":"Wifi1","rssi":-50,"encrypt":"on"},{"ssid":"wifi2","rssi":-61,"encrypt":"on"},{"ssid":"wifi3","rssi":-81,"encrypt":"of
Now if i get incomplete JSON in this format (as above) i am not able to parse the wifi name and encrypt info using StringTokenizer (it's getting way complicated and ugly).
Do you have any idea on how to parse these wifi name and encrypt info from above string. Any suggestion will be of great help.
Thanks to #pskink and #Andreas for suggesting streaming JSON parser, i tried this and it works for me. Hopefully it will be helpful for someone else as well.
public void parseWifiJSON(byte[] bytes)
{
trackerWifiScanList = readJsonStream(bytes);
// do stuff with your list
}
public List<WifiScan> readJsonStream(byte[] bytes) {
JsonReader reader = new JsonReader(new StringReader(new String(bytes)));
List<WifiScan> resultList = null;
try {
resultList = readMessagesArray(reader);
reader.close();
} catch (IOException e) {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
// Do nothing
}
}
}
return resultList;
}
public List<WifiScan> readMessagesArray(JsonReader reader) throws IOException {
ArrayList<WifiScan> messages = new ArrayList<WifiScan>();
try {
reader.beginArray();
while (reader.hasNext()) {
messages.add(readMessage(reader));
}
}catch (Exception e)
{
if (reader != null) {
try {
reader.endArray();
} catch (IOException ex) {
// Do nothing
}
}
}
return messages;
}
public WifiScan readMessage(JsonReader reader) throws IOException {
String wifissid ="";
int rssi = 0;
String encrypt="";
WifiScan wifInfo = new WifiScan();
try {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("ssid")) {
wifissid = reader.nextString();
} else if (name.equals("rssi")) {
rssi = reader.nextInt();
} else if (name.equals("encrypt")) {
encrypt = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
wifInfo.setSsid(wifissid);
wifInfo.setRssi(rssi);
wifInfo.setEncrypt(encrypt);
}catch (Exception e)
{
// JSON was not complete so just set a dummy object.
wifInfo.setSsid("");
wifInfo.setRssi(0);
wifInfo.setEncrypt("");
}
return wifInfo;
}
It has been days and I havent found any answer. And I am very new to android development. The problem I am facing is I keep on getting the error org.json.JSONException: End of input at character 0 and org.json.JSON.typeMismatch(JSON.java:111) on my onPostExecute method
#Override
protected void onPostExecute(String stringResult) {
Log.e("DB", "" + stringResult);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(stringResult);
} catch (Exception e) {
e.printStackTrace();
}
if (jsonArray != null) {
mCallback.onSuccess(jsonArray);
return;
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(stringResult);
} catch (Exception e) {
e.printStackTrace();
}
if (jsonObject != null) {
mCallback.onSuccess(jsonObject);
return;
}
mCallback.onFailed(stringResult);
}
the errors direct me to this part
try {
jsonArray = new JSONArray(stringResult);
this part too
try {
jsonObject = new JSONObject(stringResult);
} catch (Exception e) {
e.printStackTrace();
as well as from the main class method
public class PostRequest extends AsyncTask<Void, Void, String> {
please help me. thanks
Okay I think the code is not the problem as to why I cant seem to run the app. I have solved it. And the answer is not really found in what I have provided. Thanks anyway
I'm currently parsing a JSON response from the Google Translate API. I'm able to do this with no problem. Seeing as how I don't have a lot of XML experience (I'm more of an XML guy), I'm having trouble figuring out how to implement some error handling in my JSON parsing. I am using the JSON j2me library.
Here is a successful response:
{"responseData": {"translatedText":"Teks te vertaal ...","detectedSourceLanguage":"en"}, "responseDetails": null, "responseStatus": 200}
And here is an unsuccessful response:
{"responseData": null, "responseDetails": "could not reliably detect source language", "responseStatus": 400}
So, if the translation is unsuccessful, I want to put the value of "responseDetails" into a string. Here is my parsing code, which is not currently parsing out responseDetails correctly. Instead, the "catch" of the "try" is being caught.
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
} else {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate!");
}
Can anyone see where I'm going wrong?
Thanks!
Since you say the catch block is being triggered, I'd start debugging by looking at what Exception is being thrown. You could simply append your alert string to include e.toString().
So change your alert in the catch block to be:
Notify.alert("Unable to translate! " + e.toString());
And see what the actual error that's being thrown is.
Based on your comment, yes it looks like it's trying to create a JSONObject on a null value, so nest another try/catch block and parse it accordingly that way.
try {
JSONObject responseObject = new JSONObject(response);
if (responseObject != null) {
/* Try create a new JSON object from the
* responseData object. If it fails,
* display an alert */
try {
JSONObject responseData = responseObject
.getJSONObject("responseData");
if (responseData != null) {
String translatedText = responseData
.getString("translatedText");
Notify.alert(translatedText);
}
} catch (Exception e) {
String responseDetails = responseObject
.getString("responseDetails");
Notify.alert(responseDetails);
}
}
} catch (Exception e) {
Notify.alert("Unable to translate outer block!");
}