Android Firebase - Can't receive proper JSON from Firebase snapshot

you can it using gson library

       public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            /*JSONObject jsonObject = null;
            try {
                jsonObject=new JSONObject();

            } catch (JSONException e) {
                e.printStackTrace();
            }*/
            Gson gson = new Gson();
            String s1 = gson.toJson(dataSnapshot.getValue());
            JSONArray object = null;
            try {
                object = new JSONArray(s1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONArray jsonArray = object;

            Log.e("string", s1);

        }

You cannot access JSON natively in Java.

But the Firebase DataSnapshot class provides everything you need.

If you have a DataSnapshot of the data at the fbAlerts in your screenshot, you can print the date+message and recipients for each:

for (DataSnapshot alert: alerts.getChildren()) {
  System.out.println(alert.child("date").getValue();
  System.out.println(alert.child("message").getValue();
  for (DataSnapshot recipient: alert.child("recipients").getChildren()) {
    System.out.println(recipient.child("name").getValue();
  }
}

Alternatively, you can build a Java class that represents an alert. See the Firebase guide on reading data in Android for examples of that.


Use this way to convert the jsonObject form the dataSnapshot

Map<String, String> value = (Map<String, String>) dataSnapshot.getValue();
Log.i("dataSnapshot", "dataSnapshot" + new JSONObject(value));