java string 与 json 互转

1.无嵌套json

  1.1   string 转 json

              String msg="{\"id\":\"10001\",\"name\":\"肉类\",\"price\":"\"30.00"\"}";

              JSONObject jsonValue = new JSONObject(msg);

       1.2  json赋值 

             jsonValue .put("price","50.00");

        1.3 json 取值

    string price = jsonValue .getString("price");

  1.4  json 转 string 

   String msg = jsonValue .toString();

 2.有嵌套json

  2.1 json取值

    String json="{\"id\":\"10001\",\"name\":\"肉类\",\"menus\":[{\"name\":\"牛肉\",\"price\":\"30.00\"},{\"name\":\"羊肉\",\"price\":\"20.00\"}]}";

    JSONObject jsonValue = new JSONObject(msg);

         //取羊肉价格

             String menusjson = jsonValue.getString("menus");

              JSONArray menus=new JSONArray(menusjson);

    for(int i=0;i<menus.length;i++)

    {

      JSONObject  menu = menus.getJSONObject(i);

                     String name =menu.getString(''name'');

      if("羊肉".equals(name))

      {

                           String price = menu.getString("price");

                           //给羊肉价格赋值

       menu.put("price","30.00");

      }

               }

猜你喜欢

转载自www.cnblogs.com/li19950227/p/11813844.html