如何将某种格式的json加载到数据表中

时间:2017-03-09 02:45:59

标签: json datatables

我有一个JSON对象,我从Ajax请求返回,格式如下:

InputStream is;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);

    tv = (TextView)findViewById(R.id.tv);

    try {
        is = getAssets().open("html.txt");
        tv.setText(Html.fromHtml(convertStreamToString(is)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
}

如何生成一个数据表对象,其列名为" Sales1"," Sales2"等,以及每个相应列下方各行中的值?另外,假设我想在值的左侧和右侧有行标签,那可能吗?

1 个答案:

答案 0 :(得分:3)

这就是如何生成一个数据表对象,其列名为" Sales1"," Sales2"等。



$(document).ready(function() {
  var source =
  
  {data:
  [{"Sales1": "100", "Sales2": "200", "Sales3": "400"},
   {"Sales1": "150", "Sales2": "250", "Sales3": "450"}]};
   
  $('#myDataTable').dataTable({
    "data": source.data,
    "aoColumns": [{
      "mData": 'Sales1',
    }, {
      "mData": 'Sales2'
    }, {
      "mData": 'Sales3'
    }]
  })
})

<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.0/css/jquery.dataTables.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<table id="myDataTable">
  <thead>
    <tr>
      <th>Sales1</th>
      <th>Sales2</th>
      <th>Sales3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
&#13;
&#13;
&#13;