Android解析JSONObject

时间:2013-11-02 20:59:22

标签: android json parsing

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

这是我的json文件的样子:

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

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

7 个答案:

答案 0 :(得分:23)

你总是可以使用好的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
    

答案 1 :(得分:9)

更新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
  5. 对Gson的替代,您可以使用Jackson

    1. Jackson in 5 minutes
    2. how to convert java object to and from json
    3. 这些库基本上将您的JSON解析为您指定的Java类。

答案 2 :(得分:9)

知道字符串是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);

答案 3 :(得分:2)

此部分在onBackground

中的AsyncTask中进行
  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;

}
  }

答案 4 :(得分:0)

我建议你使用像gson这样的库,@ jmeier在他的回答中写道。但是如果你想用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 :(得分:0)

请结帐ig-json parserLogan Square以获取快速轻便的JSON库。

相比之下,这是Logan Square开发人员的统计数据。 enter image description here

答案 6 :(得分:0)

在这里,您可以解析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();
}