How to call the JSON object in Android

后端 未结 5 1242
小鲜肉
小鲜肉 2020-12-21 06:09

I am new to the android development. i am having the following android code to call the json

  try {

        JSONObject jsonObject = new JSONObject(resul         


        
相关标签:
5条回答
  • 2020-12-21 06:46

    Try this

    JSONObject jsonObject = new JSONObject(result);
    JSONArray jArray =json.getJSONArray("enterjsonarraynamehere");
    
    for (int i=0; i < jArray.length(); i++)
    {
        try {
            JSONObject oneObject = jArray.getJSONObject(i);
            // Pulling items from the array
            String cust= oneObject.getString("CUSTOMER_ID");
        } catch (JSONException e) {
            // Oops something went wrong
        }
    }
    

    Im assuming your json is something like this

    <somecode>
        {
            "enterjsonarraynamehere": [
                {  "0":"1",
                   "CUSTOMER_ID":"1"
                },
                {   "0":"2",
                   "CUSTOMER_ID":"2"
                } 
            ],
            "count": 2
        }
    <somecode>
    
    0 讨论(0)
  • 2020-12-21 07:00

    if you have any problems regarding to your JSON format first validate it through this site http://jsonlint.com/

    then for parsing

    JSONObject jsonObject = new JSONObject(result);
    // since your value for CUSTOMER_ID in your json text is string then you should get it as 
    // string and then convert to an int
    returnUsername1 = Integer.parseInt(jsonObject.getString("CUSTOMER_ID"));
    
    0 讨论(0)
  • 2020-12-21 07:06

    Generally, to get a JSONObject from a JSONArray:

    JSONObject jsonObject = jsonArray.getJSONObject(0); //0 -> first object
    

    And then

    int userID = jsonObject.getInt("CUSTOMER_ID");
    
    0 讨论(0)
  • 2020-12-21 07:06

    CUSTOMER_ID is not considered a JSONObject in this case. If jsonObject is what you think it is, then you should be able to access it with jsonObject.getString("CUSTOMER_ID")

    0 讨论(0)
  • What you have is a Json Array

    JSONArray jsonarray = new JSONArray(result); // result is a Array
    

    [ represents json array node

    { represents json object node

    Your Json. Do you need a Json array twice?

      [ // array
        [ //array
            { // object
                "0": "1",  
                "CUSTOMER_ID": "1"
            }
        ]
       ]
    

    Parsing

    JSONArray jsonArray = new JSONArray(result);
    JSONArray ja= (JSONArray) jsonArray.get(0);
    JSONObject jb = (JSONObject) ja.get(0);
    String firstvalue = jb.getString("0");
    String secondvalue = jb.getString("CUSTOMER_ID");
    Log.i("first value is",firstvalue);
    Log.i("second value is",secondvalue);
    

    LogCat

     07-22 14:37:02.990: I/first value is(6041): 1
     07-22 14:37:03.048: I/second value is(6041): 1
    
    0 讨论(0)
提交回复
热议问题