代码之家  ›  专栏  ›  技术社区  ›  Rajesh K

如何从Json文件中获取值

  •  0
  • Rajesh K  · 技术社区  · 7 年前

    这是我的Json格式示例

    {
    "par_a":".....",
    "par_b": [ {
    "b1":".....",
    "b2":".....",
    "b3":".....",
    "b4":".....",
    "b5":".....",
    "b6":".....",
    "b7":".....",
    "b8":".....",
    "b9":".....",
    "b10": { "b10-1":".....", "b10-2":".....", "b10-3":"....." } ,
    "b11": { "b11-1": ["....." ], "b11-2": ["....." ] } , 
    "b13":"......."
    } ] 
    }
    

    我没有办法联系API的所有者并了解其工作原理,因此我非常感谢您的帮助。

    我在网上看到过很多帖子,但我从未见过像我这样的Json格式,因此没有一个解决方案适合我。

    6 回复  |  直到 7 年前
        1
  •  1
  •   Mohammed    7 年前

    一个很好的解决方法是创建一个与您从服务器收到并使用的响应相对应的模型 GSON 库,您可以轻松地将json反序列化到您的模型中。 您的模型如下所示:

    public class MyResponseModel {
    
        @SerializedName("par_a")
        private String parameterA;
        @SerializedName("par_b")
        private List<AnotherModel> parametersB;
        /.../
    }
    
        2
  •  1
  •   Prince Dholakiya    7 年前

    如果您从json文件获取数据并将其存储在项目中,那么

    Gson gson = new Gson();
            String customRatioResponse = LocalUtils.loadJSONFromAsset(getActivity(), "custom_ratio.json"); // here custom_ratio.json is my json file. it's store in assets folder of project
            CustomRatioList getSampleImageResponse = gson.fromJson(customRatioResponse, CustomRatioList.class); // here CustormRatioList is my POJO file
            Log.i(TAG, "getAllCategory() -> Offline list size: " + (getSampleImageResponse.getCustomRatio() != null ? getSampleImageResponse.getCustomRatio().size() : 0));
            return getSampleImageResponse.getCustomRatio();
    

    在这里,如果您的Json文件包含太多数据或数据列表,那么它将为您提供arrayList类型的数据。

    LocalUtils.java

    public class LocalUtils {
    
        public static String loadJSONFromAsset(Context context, String jsonFilePath) {
            String json = null;
            try {
                InputStream is = context.getAssets().open(jsonFilePath);
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (Throwable e) {
                e.printStackTrace();
                return "";
            }
            return json;
        }
    }
    

    如果您将获得json的pojo,请转到 http://www.jsonschema2pojo.org/ 粘贴示例数据json并获取pojo结构。谢谢你的阅读。

        3
  •  1
  •   Mathieu Heuzey    7 年前

    你有一个很好的库来做这件事,使用GSON-lib。您只需创建一个表示Json文件的对象,当您解码它时,它就会感觉到您的对象和Json数据!

        4
  •  1
  •   Ramkumar.M    7 年前

    这样

        public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getActivity().getAssets().open("filename.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }
    

    然后解析json

            JSONObject obj = new JSONObject(loadJSONFromAsset());
    
        5
  •  1
  •   Pooja Rajendran C    7 年前
    1. 为android studio安装DTO生成器插件(“这对将来的工作也很有用”):文件->设置->插件->搜索DTO并安装
    2. 创建一个简单的类,比如DataRetriever。将光标放在该类中,然后按Alt+insert->从JSON中选择DTO
    3. 在窗口中输入获取的JSON,然后按generate。这将使您的类具有Json中的所有属性。为属性创建getter和setter。结果会是这样的

      public class DataRetriever {
      
      @Expose
      @SerializedName("par_b")
      private List<Par_bEntity> mPar_b;
      @Expose
      @SerializedName("par_a")
      private String mPar_a;
      
      public List<Par_bEntity> getmPar_b() {
      return mPar_b;
      }
      
      public void setmPar_b(List<Par_bEntity> mPar_b) {
      this.mPar_b = mPar_b;
      }
      
      public String getmPar_a() {
      return mPar_a;
      }
      
      public void setmPar_a(String mPar_a) {
      this.mPar_a = mPar_a;
      }
      /**
       * Similar to these getter and setter, you can add getter and setter for sub 
       classes also
       */
        }
      
        class Par_bEntity {
      
         @Expose
      @SerializedName("b13")
      private String mB13;
      @Expose
      @SerializedName("b11")
      private B11Entity mB11;
      @Expose
      @SerializedName("b10")
      private B10Entity mB10;
      @Expose
      @SerializedName("b9")
      private String mB9;
      @Expose
      @SerializedName("b8")
      private String mB8;
      @Expose
      @SerializedName("b7")
      private String mB7;
      @Expose
      @SerializedName("b6")
       private String mB6;
      @Expose
      @SerializedName("b5")
      private String mB5;
      @Expose
      @SerializedName("b4")
      private String mB4;
      @Expose
      @SerializedName("b3")
      private String mB3;
      @Expose
      @SerializedName("b2")
      private String mB2;
      @Expose
      @SerializedName("b1")
      private String mB1;
      }
      
      class B10Entity {
         @Expose
        @SerializedName("b10-3")
       private String b10_3;
       @Expose
       @SerializedName("b10-2")
       private String b10_2;
        @Expose
       @SerializedName("b10-1")
        private String b10_1;
        }
      
        class B11Entity {
       @Expose
       @SerializedName("b11-2")
       private List<String> b11_2;
       @Expose
       @SerializedName("b11-1")
       private List<String> b11_1;
      }
      
    4. 在获取json字符串的位置,通过调用

      DataRetriever mDataRetriever = new Gson().fromJson(jsonString, DataRetriever.class);
      

      使用mDataRetriever对象和getter方法,您可以使用

      Ex : mDataRetriever.getmPar_a()for value “par_a”
      
        6
  •  -1
  •   Gourango Sutradhar    7 年前

    假设您正在尝试查找的字符串值 b10-1 :

    代码如下所示:

    String json = "{par_a:.....,par_b: [ {b1:.....,b2:.....,b3:.....,b4:.....,b5:.....,b6:.....,b7:.....,b8:.....,b9:.....,b10: { b10-1:....., b10-2:....., b10-3:..... } ,b11: { b11-1: [..... ], b11-2: [..... ] } , b13:.......} ]}";
    
    try{
        String result = new JSONObject(json).getJSONArray("par_b").getJSONObject(0).getJSONObject("b_10").getString("b10-1");
    }catch(Exception e){
    
    }