11

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 :/

4

7 回答 7

25

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
    
于 2013-11-02T21:25:20.643 回答
10

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.

于 2013-11-02T21:00:51.523 回答
8

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);
于 2013-11-02T21:38:21.247 回答
2

This part do in onBackground in 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;

}
  }
于 2013-11-02T21:16:46.123 回答
0

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

    }

}
于 2013-11-02T21:32:05.917 回答
0

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

于 2017-08-01T09:04:16.037 回答
0

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();
}
于 2018-03-14T06:36:30.163 回答