parsing Json in Android Studio when result is empty - json

I try to load datas from a Json that is on my server to my smartphone.
When the json is like this, it works and i get the label "spanishguitar":
{"file": "image.jpg", "objects": [{"bbox": [611, 82, 1231, 1265], "label": "spanishguitar", "prob": 0.991}]}
Here is my code:
public void updateLabel() {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
instrumentname = jsonResult.objects.get(0).label;
But sometimes the json is empty like this:
{"file": "image.jpg", "objects": []}
So my plan is that if objects == null to get something like:
Toast.makeText(getApplicationContext(), "Uuuups, itś empty", Toast.LENGTH_SHORT).show();
Do you know how to parse the json, so that i get a message in the case of an empty "objects"?
Thank you!
Now it works. Here is my code:
#RequiresApi(api = Build.VERSION_CODES.N)
private void empty() throws IOException {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "objects.json");
HttpResponse jsonResponse = client.execute(getJson);
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(String.valueOf(json));
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if (objects == null || objects.size() == 0) {
/////////////
runOnUiThread(new Runnable() {
#Override
public void run() {
noResult.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Identification failed", Toast.LENGTH_SHORT).show();
}});
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
} else {
updateLabel();
}
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
Thank you a lot for your help!

'Empty' is not 'null'.You can use
ArrayUtils.isEmpty(objects)
or
objects == null || objects.length() == 0
to detect whether you got an empty objects.
I writed a demo for you:
import com.google.gson.*;
public class Main
{
public static void main(String[] args)
{
JsonParser parser = new JsonParser();
// JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": []}");
JsonElement element= parser.parse("{\"file\": \"image.jpg\", \"objects\": [{\"bbox\": [611, 82, 1231, 1265], \"label\": \"spanishguitar\", \"prob\": 0.991}]}");
JsonObject obj = element.getAsJsonObject();
JsonArray objects = obj.getAsJsonArray("objects");
if(objects == null || objects.size() == 0) {
System.out.println("objects is empty");
}else{
JsonObject firstObj = objects.get(0).getAsJsonObject();
System.out.println("objects[0].label="+firstObj.get("label"));
}
}
}

Related

Java/Android: Backslashes in JSON in Double Quotation places

I try to send "POST" request to serwer. Request includes JSON. Server returns "ok" or my JSON (in value of "message" key), if data in not correct. And I get strange backslashes ( \ sing) in my JSON, sent to server.
I get JSON response:
{"message":{"{\"phone_number\":\"_380661111111\",\"password\":\"112233aa\",\"military_id\":\"12345\",\"email\":\"won#mail_ru\"}":""}}
Normal JSON:
{"phone_number":"380666320670","password":"112233aa","military_id":"12345","email":"wovilon#mail.ru"}
Full code:
class SendLoginData extends AsyncTask<Void, Void, Void> {
String[] key,value;
String mResultString;
SendLoginData(String[] inKey, String[] inValue ){
this.key=new String[inKey.length];
this.value=new String[inValue.length];
this.key=inKey;
this.value=inValue;
}
String resultString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {// http://oasushqg.beget.tech/users
String myURL = "http://y937220i.bget.ru/users";
byte[] data = null;
InputStream is = null;
try {
URL url = new URL(myURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
for (int i=0; i<this.key.length; i++) {
jsonParam.put(this.key[i], this.value[i]);
}
data=jsonParam.toString().getBytes("UTF-8");
os.write(data);
Log.d("MyLOG", "data is next: "+new String(data, "UTF-8"));
data = null;
conn.connect();
int responseCode= conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (responseCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
JSONObject jsonObj=new JSONObject(resultString);
mResultString=jsonObj.getString("message");
} else {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(resultString != null) {
Log.d("MyLOG", "postExecute run");
Log.d("MyLOG", mResultString);
}
}}

Json Parse Failed- javafx

I am writing javafx app
I try to sava and load data using JSON
#FXML
private void OpenEvent(ActionEvent event) throws IOException, ParseException, Exception {
String jsonString = new String();
FileReader fileReader = new FileReader("test.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println("Check open event here");
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString += inputLine;
}
bufferedReader.close();
System.out.println(jsonString);
//GOOD HERE
JSONArray jlist;
try {
jlist = parseJsonArray(jsonString);
} catch (Exception ex) {
throw ex;
}
for (Object e : jlist) {
try {
JSONObject jentryParsed = (JSONObject) e;
LocalEvent entry = new LocalEvent();
entry.initFromJsonString(jentryParsed.toJSONString());
} catch (Exception ex) {
throw ex;
}
}
}
public JSONArray parseJsonArray(String jsonString) throws Exception {
JSONArray jlist;
JSONParser parser = new JSONParser();
System.out.println("Check parse here");
System.out.println(jsonString);
try {
jlist = (JSONArray) parser.parse(jsonString);
} catch (Exception ex) {
throw ex;
}
System.out.println("parsed finished");
if (jlist == null) {
System.out.println("jlist is null");
return null;
} else {
return jlist;
}
}
and here is my JSON file
[{"Description":"11111","Name":"11111","Datetime":2016-04-27},{"Description":"2222","Name":"2222","Datetime":2016-04-14}]
error:
Caused by: Unexpected token VALUE(-4) at position 54.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at todolist.MainController.parseJsonArray(MainController.java:276)
at todolist.MainController.OpenEvent(MainController.java:250)
... 50 more
It seems the json parse is failed.
is here anything wrong with my JSON file?
Thanks!!!!!!!
or the parse cannot recognize "-" in the datetime??

Converting finalBufferData into img url to display

I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String 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 = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} 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(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> 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 = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} 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<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.

Error of sendUserActionEvent() mView == null is coming

I am parsing a json response file got through the Volley Request Libraries and populating List by the json array.
public void getAllContacts() {
queue = Volley.newRequestQueue(getApplicationContext());
String tag_json_obj = "json_obj_req";
String url = "http://52.25.169.219:3000/users";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray cast = response.getJSONArray("users");
for (int i=0; i<cast.length(); i++)
{
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
String phoneno = actor.getString("contact");
name1.add(name);
phno1.add(phoneno);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
VolleyLog.d("Tag", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Error in fetching contacts", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjReq);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.show();
}
But getting volley error and toast as error in fetching contacts.
My json file format is
{"users":"[{\"id\":1,\"name\":\"test_name\",\"contact\":\"23456543\",\"gender\":\"F\",\"age\":234,\"city\":\"delhi\",\"state\":\"india\",\"created_at\":\"2015-07-19T17:58:42.000Z\",\"updated_at\":\"2015-07-19T17:58:42.000Z\",\"district\":\"test_district\"},{\"id\":2,\"name\":\"test_name\",\"contact\":\"23456543\",\"gender\":\"F\",\"age\":234,\"city\":\"delhi\",\"state\":\"india\",\"created_at\":\"2015-07-19T17:58:42.000Z\",\"updated_at\":\"2015-07-19T17:58:42.000Z\",\"district\":\"test_district\"}]"}
Error is
08-02 21:20:57.264: E/ViewRootImpl(31835): sendUserActionEvent() mView == null

how to read a json file by hashMap in java

I have a very simple question. I want to read a json file by hashMap in java.
For example I have a json file like this:
{
"list": [
{
"ID" : "#12354667",
"value" : "data1."
}
{
"ID" : "#12345789",
"value" : "data2"
}
And whenever I call the id it returns the value. I have written this but I do not know how to read the file. Any help?
Thanks,
private JsonReader() throws IOException {
//readfile?
this.messages = new HashMap<String, String>();
}
public String getValue(final String ID)
{
if (this.messages.containsKey(ID))
{
return this.messages.get(value);
}
return "";
}
You can use JSONParser and FileReader to read your file into your Application. I'm not quite sure if this is what you searched for, but you can try it. You only have to give your ID to this method.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\yourFile.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray list= (JSONArray) jsonObject.get("list");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String id= (String) jsonObject.get("ID");
if(id.equals(hereYourFinalString ID)){
String value = (String) jsonObject.get("value");
System.out.println(value);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}