Разбор массива Json без имени массива - PullRequest
0 голосов
/ 16 мая 2018
LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data;
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;
String x, y;

public Graph_Fragment() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_graph_, container, false);
}

HttpURLConnection connection;

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
    graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
    graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
    graph = (GraphView) getView().findViewById(R.id.graph1);
    //graphDataClass gdc = new graphDataClass();
    //gdc.execute();


    String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\"," +
            "\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";

    String data = "";
    try {



        // Create the root JSONObject from the JSON string.
        JSONObject  jsonRootObject = new JSONObject(strJson);

        //Get the instance of JSONArray that contains JSONObjects
        JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");

        //Iterate the jsonArray and print the info of JSONObjects
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());

            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";


        }
        graphOneTV.setText(data);
    } catch (JSONException e) {e.printStackTrace();}}}

Итак, я пытался проанализировать массив JSON с помощью приведенного выше кода, и это сработало, но позже я пытался извлечь JSON с моего локального ПК, но у этого JSON нет имени массива.JSON, который я пытаюсь получить, приведен ниже.

[{"twitter":"200","googleplus":"60"},{"twitter":"150","googleplus":"180"},{"twitter":"90","googleplus":"120"}]

Код для извлечения и анализа этого массива JSON приведен ниже.

LineGraphSeries<DataPoint> series;
ArrayList<HashMap<String, String>> arrayListData;
public static String data,data2;
TextView graphOneTV, graphTwoTV, graphThreeTV;
GraphView graph;
//String x, y;

public Graph_Fragment() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_graph_, container, false);
}

HttpURLConnection connection;

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    graphOneTV = (TextView) getView().findViewById(R.id.TVGraph1);
    graphTwoTV = (TextView) getView().findViewById(R.id.TVGraph2);
    graphThreeTV = (TextView) getView().findViewById(R.id.TVGraph3);
    graph = (GraphView) getView().findViewById(R.id.graph1);
    graphDataClass gdc = new graphDataClass();
    gdc.execute();


    /*String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\"," +
            "\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";

    String data = "";
    try {



        // Create the root JSONObject from the JSON string.
        JSONObject  jsonRootObject = new JSONObject(strJson);

        //Get the instance of JSONArray that contains JSONObjects
        JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");

        //Iterate the jsonArray and print the info of JSONObjects
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());

            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";


        }
        graphOneTV.setText(data);
    } catch (JSONException e) {e.printStackTrace();}
    */

}
    public class graphDataClass extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {

            try {
                URL url = new URL("http://192.168.1.34/getGraphData.php?");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = connection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while (line != null) {
                    line = bufferedReader.readLine();
                    data = data + line;
                }

                JSONObject  jsonRootObject = new JSONObject(data);

                JSONArray jsonArray = jsonRootObject.optJSONArray("");

                for(int i=0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    int x = Integer.parseInt(jsonObject.optString("twitter").toString());
                    int y = Integer.parseInt(jsonObject.optString("googleplus").toString());


                    data2 += "Node" + i + " : \n id= " + x + " \n Name= " + y ;
                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }


        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            graphOneTV.setText(data2);

        }
    }

}

Но, как сказано ранее, этот JSONне имеет имени массива, так что я должен написать место, где требуется имя массива.

JSONArray jsonArray = jsonRootObject.optJSONArray ("Что показать, я пишу ЗДЕСЬ ???? (Нет имени массива в JSON!!! ");

Ответы [ 4 ]

0 голосов
/ 17 мая 2018

Попробуйте так:

ArrayList<HashMap<String, String>> arrayListSocial = new ArrayList<>();

String string = "[{\"twitter\":\"200\",\"googleplus\":\"60\"},{\"twitter\":\"150\",\"googleplus\":\"180\"},{\"twitter\":\"90\",\"googleplus\":\"120\"}]";
try {
    JSONArray jsonarray = new JSONArray(string);
    for (int i = 0; i < jsonarray.length(); i++) {
        JSONObject jsonobject = jsonarray.getJSONObject(i);
       String socailTwiter= jsonobject.getString("twitter");
        String socailGplus = jsonobject.getString("googleplus");

        Log.e("socailTwiter",socailTwiter);

        HashMap<String, String> hashMap = new HashMap<>();

        hashMap .put("twitter",socailTwiter);
        hashMap .put("googleplus",socailGplus );


        arrayListSocial.add(hashMap);
    }

}catch (Exception e){
   e.printStackTrace();
}
0 голосов
/ 16 мая 2018

изменить файл кода php

<?php 
    if($connect){
        die('Could Not Connect :'.mysqli_error());
    }
    $result = mysqli_query($connect,"SELECT * FROM table_name);
    while($row=mysqli_fetch_assoc($result)){
         $output[]=$row;
    }
    print(json_encode(array('yourarrayname' =>$output),JSON_PRETTY_PRINT));
    mysqli_close($connect);
?>

JSONArray jsonArray = jsonRootObject.optJSONArray("yourarrayname_define_php_json_file");
0 голосов
/ 16 мая 2018

Надеюсь, это сработает для вас.

разбор вот так.

  try {
         JSONArray jsonArray = new JSONArray(data);
             for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String twitter = jsonObject.getString("twitter");
                    String googleplus = jsonObject.getString("googleplus");
                    Log.e("googleplus", googleplus);
                    Log.e("twitter", twitter);
                }
            } catch (Exception e) {

            }

И добавить данные в arraylist.

0 голосов
/ 16 мая 2018

Если вы знаете, что ваша строка является массивом JSON, проанализируйте строку с JSONArray вместо JSONObject.Затем используйте методы доступа к массиву, такие как JSONArray.get.

JSONArray jsonArray = new JSONArray(json);
JSONObject first = jsonArray.optJSONObject(0);

В противном случае используйте gson :

Type collectionType = new TypeToken<Collection<Map<String, Object>>>(){}.getType();
Collection<Map<String, Object>> items = gson.fromJson(json, collectionType);

Или Джексон :

TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>();
List<Map<String, Object>> items = new ObjectMapper().readValue(json, typeReference);
...