【问题标题】:Android parse JSONObjectAndroid 解析 JSONObject
【发布时间】:2013-11-13 20:04:48
【问题描述】:

我在将 json 解析到我的 Android 应用程序时遇到了一点问题。

这就是我的 json 文件的样子:

{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}

如您所见,这种结构有点奇怪。我不知道如何在我的应用程序中读取该数据。我注意到这些都是对象而不是数组:/

【问题讨论】:

    标签: android json parsing


    【解决方案1】:

    2018 年更新

    5 年后,在 android 上解析 json 有了新的“标准”。它被称为moshi,可以认为它是GSON 2.0。它非常相似,但修复了设计错误,这是您开始使用它时的第一个障碍。

    https://github.com/square/moshi

    首先将其添加为 mvn 依赖项,如下所示:

    <dependency>
      <groupId>com.squareup.moshi</groupId>
      <artifactId>moshi-kotlin</artifactId>
      <version>1.6.0</version>
    </dependency>
    

    添加后我们可以这样使用(取自示例):

    String json = ...;
    
    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
    
    BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
    System.out.println(blackjackHand);
    

    他们的 GitHub 页面上的更多信息 :)

    [旧]

    我建议使用Gson

    这里有一些教程链接:

    1. how to convert java objecto from json format using GSON
    2. Parse JSON file using GSON
    3. Simple GSON example
    4. Converting JSON data to Java object

    您可以使用 Jackson 的 Gson 替代方案

    1. Jackson in 5 minutes
    2. how to convert java object to and from json

    这些库基本上将您的 JSON 解析为您指定的 Java 类。

    【讨论】:

      【解决方案2】:

      这部分做在onBackgroundAsyncTask

        JSONParser jParser = new JSONParser();
       JSONObject json = jParser.getJSONFromUrl(url);
      
      
              try {
      
                  result = json.getString("internalName");
                                  data=json.getString("dataVersion");
                            ect..
      
      
              } catch (JSONException e) {
                  e.printStackTrace();
              }
      

      JsonParser

       public class JSONParser {
      
      static InputStream is = null;
      static JSONObject jObj = null;
      static String json = "";
      
      // constructor
      public JSONParser() {
      
      }
      
      public JSONObject getJSONFromUrl(String url) {
      
          // Making HTTP request
          try {
              // defaultHttpClient
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpPost httpPost = new HttpPost(url);
              HttpResponse httpResponse = httpClient.execute(httpPost);
              HttpEntity httpEntity = httpResponse.getEntity();
              is = httpEntity.getContent();
      
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      
          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "utf-8"), 8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
              is.close();
              json = sb.toString();
          } catch (Exception e) {
              Log.e("Buffer Error", "Error converting result " + e.toString());
          }
      
          // try parse the string to a JSON object
          try {
              jObj = new JSONObject(json);
          } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
          }
      
          // return JSON String
          return jObj;
      
      }
        }
      

      【讨论】:

        【解决方案3】:

        您始终可以使用旧的 json.org lib。在您的 Java 代码中:

        • 首先将你的json文件内容读入String
        • 然后解析成JSONObject

          JSONObject myJson = new JSONObject(myJsonString);
          // use myJson as needed, for example 
          String name = myJson.optString("name");
          int profileIconId = myJson.optInt("profileIconId");
          // etc
          

        【讨论】:

          【解决方案4】:

          我建议您使用像 @jmeier 在他的回答中所写的 gson 这样的库。但是如果你想用android的默认值处理json,你可以使用这样的东西:

          public class MainActivity extends Activity {
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
          
                  String s = new String("{\"internalName\": \"domin91\",\"dataVersion\": 0,\"name\": \"Domin91\",\"profileIconId\": 578,\"revisionId\": 0,}");
          
                  try {
                      MyObject myObject = new MyObject(s);
                      Log.d("MY_LOG", myObject.toString());
                  } catch (JSONException e) {         
                      Log.d("MY_LOG", "ERROR:" + e.getMessage());
                  }
          
          
              }
          
              private static class MyObject {
                  private String internalName;
                  private int dataVersion;
                  private String name;
                  private int profileIconId;
                  private int revisionId;
          
                  public MyObject(String jsonAsString) throws JSONException {
                      this(new JSONObject(jsonAsString));
                  }
          
                  public MyObject(JSONObject jsonObject) throws JSONException {
                      this.internalName = (String) jsonObject.get("internalName");
                      this.dataVersion = (Integer) jsonObject.get("dataVersion");
                      this.name = (String) jsonObject.get("name");
                      this.profileIconId = (Integer) jsonObject.get("profileIconId");
                      this.revisionId = (Integer) jsonObject.get("revisionId");
                  }
          
                  @Override
                  public String toString() {
                      return "internalName=" + internalName + 
                              "dataVersion=" + dataVersion +
                              "name=" + name +
                              "profileIconId=" + profileIconId + 
                              "revisionId=" + revisionId;
                  }
          
              }
          
          }
          

          【讨论】:

            【解决方案5】:

            知道字符串是JSONArray还是JSONObject

            JSONArray字符串是这样的

            [{
            "internalName": "blaaa",
            "dataVersion": 0,
            "name": "Domin91",
            "profileIconId": 578,
            "revisionId": 0,
            },
            {
            "internalName": "blooo",
            "dataVersion": 0,
            "name": "Domin91",
            "profileIconId": 578,
            "revisionId": 0,
            }]
            

            这个字符串作为JSONOject

            {
            "internalName": "domin91",
            "dataVersion": 0,
            "name": "Domin91",
            "profileIconId": 578,
            "revisionId": 0,
            } 
            

            但是如何从JSONArrayJSONObject 调用元素呢?

            JSNOObject 信息这样调用

            首先用数据填充对象

            JSONObject object = new JSONObject(
            "{
            \"internalName\": \"domin91\",
            \"dataVersion\": 0,
            \"name\": \"Domin91\",
            \"profileIconId\": 578,
            \"revisionId\": 0,
            }"
            );
            

            现在让我们从对象调用信息

            String myusername = object.getString("internalName");
            int dataVersion   = object.getInt("dataVersion");
            

            如果你想从JSONArray调用信息,你必须知道对象位置号是什么,否则你必须循环JSONArray来获取信息,例如

            循环数组

            for ( int i = 0; i < jsonarray.length() ; i++)
            {
               //this object inside array you can do whatever you want   
               JSONObject object = jsonarray.getJSONObject(i);
            }
            

            如果我知道JSONArray 中的对象位置,我会这样称呼它

            //0 mean first object inside array
             JSONObject object = jsonarray.getJSONObject(0);
            

            【讨论】:

              【解决方案6】:

              请查看ig-json parserLogan Square 以获取快速、轻便的 JSON 库。

              为了比较,这是来自 Logan Square 开发者的统计数据。

              【讨论】:

                【解决方案7】:

                在这里您可以解析资产文件夹中的任何文件 从 assets 文件夹中获取文件

                public void loadFromAssets(){
                    try {
                        InputStream is = getAssets().open("yourfile.json");
                        readJsonStream(is);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                

                将 JSON 转换为您的类对象

                public void  readJsonStream(InputStream in) throws IOException {
                    Gson gson = new Gson();
                    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
                    reader.setLenient(true);
                    int size = in.available();
                    Log.i("size", size + "");
                
                    reader.beginObject();
                
                
                    long starttime=System.currentTimeMillis();
                    while (reader.hasNext()) {
                        try {
                            Yourclass message = gson.fromJson(reader, Yourclass.class);
                        }
                        catch (Exception e){
                            Toast.makeText(this, e.getCause().toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    reader.endObject();
                    long endtime=System.currentTimeMillis();
                    long diff=endtime-starttime;
                    int seconds= (int) (diff/1000);
                    Log.i("elapsed",seconds+"");
                    reader.close();
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-07-07
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多