Android parse JSONObject

2019-01-17 01:57发布

I've got a little problem with parsing json into my android app.

This is how my json file looks like:

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

As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/

7条回答
老娘就宠你
2楼-- · 2019-01-17 02:17

UPDATE 2018

After 5 years there is a new "standard" for parsing json on android. It's called moshi and one can consider it GSON 2.0. It's very similar but with design bugs fixed that are the first obstacles when you start using it.

https://github.com/square/moshi

First add it as a mvn dependency like this:

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

After adding it we can use like so (taken from the examples):

String json = ...;

Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);

BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);

More infos on their GitHub page :)

[old]

I would recommend using Gson.

Here are some links for tutorials:

  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

An alternative to Gson you could use Jackson.

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

This libraries basically parse your JSON to a Java class you specified.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-17 02:24

I suggest you to use a library like gson as @jmeier wrote on his answer. But if you want to handle json with android's defaults, you can use something like this:

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;
        }

    }

}
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-17 02:24

Please checkout ig-json parser or Logan Square for fast and light JSON library.

For comparison, this is the stats from Logan Square developer. enter image description here

查看更多
不美不萌又怎样
5楼-- · 2019-01-17 02:30

to know if string is JSONArray or JSONObject

JSONArray String is like this

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

and this String as a JSONOject

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

but how to call elements from JSONArray and JSONObject ?

JSNOObject info called like this

first fill object with data

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

now lets call information from object

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

If you want to call information from JSONArray you must know what is the object position number or you have to loop JSONArray to get the information for example

looping array

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

if i know the object position inside JSONArray ill call it like this

//0 mean first object inside array
 JSONObject object = jsonarray.getJSONObject(0);
查看更多
劳资没心,怎么记你
6楼-- · 2019-01-17 02:32

You can always use good old json.org lib. In your Java code :

  • First read your json file content into String;
  • Then parse it into JSONObject:

    JSONObject myJson = new JSONObject(myJsonString);
    // use myJson as needed, for example 
    String name = myJson.optString("name");
    int profileIconId = myJson.optInt("profileIconId");
    // etc
    
查看更多
倾城 Initia
7楼-- · 2019-01-17 02:36

Here you can parse any file from assets folder fetch file from assets folder

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

Convert JSON to your class object

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();
}
查看更多
登录 后发表回答