解析具有数组名称的Json数组

时间:2018-05-16 07:48:48

标签: java android arrays json jsonparser

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数组并且它工作但后来我试图从我的localhost pc获取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 :(得分:0)

如果您知道您的字符串是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);

jackson

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

答案 1 :(得分:0)

修改php代码文件

c_str()

答案 2 :(得分:0)

我希望这对你有用。

像这样解析。

  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。

答案 3 :(得分:0)

尝试这种方式:

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();
}