从 json 数组读取数据以绘制图表

Reading data from json array to plot in graph

所以我使用 MPandroid 图表依赖项在 android 应用程序上绘制图表。为此,我将数据添加到图表的 class 条目的 ArrayList 中。 我现在手动添加数据,但我想解析 json 文件中的数据并将其添加到图表中。谁能告诉我如何读取 Json 数组的各个数据元素以添加到图形中。

这是我用来读取 json file.I 文件的代码,该文件位于我的资产文件夹中。

  try {
        InputStream is=getAssets().open("gaitdata.json");
        int size=is.available();
        byte[] buffer=new byte[size];
        is.read(buffer);
        is.close();
        json=new String(buffer,"UTF-8");
        JSONArray jsonArray=new JSONArray(json);

            for(int i=0;i<jsonArray.length();i++){
                JSONObject obj=jsonArray.getJSONObject(i);
                if(obj.getString("name").equals("kinematics")){
                    hipvalue.add(obj.getString("hip_min"));


              }
            }

这也是我要阅读的 json 文件。

{
 "name":"kinematics",
 "hip_min":[1.2,5.67,2.34,6.8]
}

我也想要浮点值,但由于它不起作用,所以我使用 obj.getString() 来获取 json 的 "hip_min" 值。

最后,这是我手动将数据添加到数组列表的方式。

ArrayList<Entry> entries=new ArrayList<>();
        entries.add(new Entry(0,19.85f));

要将 Json Arry 转换为浮动数组,您可以尝试以下代码。

   String value = "{'name':'kinematics','hip_min':[1.2,5.67,2.34,6.8]}";
        JSONObject obj = new JSONObject(value);
        List hip_min = new ArrayList<Float>();
        JSONArray jsonArray;

        jsonArray = obj.getJSONArray("hip_min");

        for (Object item : jsonArray
        ) {
            hip_min.add(item);
        }
        System.out.println("Size : " + hip_min.size());

对于图表

 int i=0;
        for (Object item:hip_min
             ) {
            entries.add(new Entry(i,item))
                    i=i+2;


        }

i 的值用于水平移动。 希望对您有所帮助。