package цукаука;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class ReadJsonAccounts {
public ReadJsonAccounts(Context context,String url) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>(){
@Override
public void onResponse(String response) {
try {
Log.i("Info", response);
JSONObject object = new JSONObject(EncodingToUTF8(response));
JSONArray jsonArray = object.getJSONArray("users");
ArrayList<JSONObject> listItems = getArrayListFromJSONArray(jsonArray);
// чтото делаем с получившимся JSON
if(jsonArray!= null){
for(int i = 0; i<jsonArray.length();i++){
Log.i("Info", jsonArray.getJSONObject(i).getString("email"));
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public static String EncodingToUTF8(String response){
try {
byte[] code = response.toString().getBytes("ISO-8859-1");
response = new String(code, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
return response;
}
private ArrayList<JSONObject> getArrayListFromJSONArray(JSONArray jsonArray){
ArrayList<JSONObject> aList = new ArrayList<JSONObject>();
try {
if(jsonArray!= null){
for(int i = 0; i<jsonArray.length();i++){
aList.add(jsonArray.getJSONObject(i));
}
}
}catch (JSONException js){
js.printStackTrace();
}
return aList;
}
}