Get properties of a JSON

2

I have this JSON , and I want to analyze it in Android :

  

{"usd": {"code": "USD", "alphaCode": "USD", "numericCode": "840", " name ": "US Dollar", " rate ": 0.062953567779141," date ":" Sun, 4 Dec 2016 12:00:01 GMT "}," eur ": {" code ":" EUR "," alphaCode ":" EUR "," numericCode ":" 978 "," name ":" Euro "," rate ": 0.059052814030065," date ":" Sun, 4 Dec 2016 12: 00:01 GMT "}}

I want to get name and rate . I do not know if I should create a JSONArray like this:

JSONArray objetoName = jsonObject.getJSONObject("name");

... or if you go to String .

for(int i=0;i<objetoName.length();i++){
    JSONObject stringer = objetoName.getJSONObject(i);
    stringArray[i] = stringer.getString("name");
}
    
asked by Los Milton 04.12.2016 в 17:24
source

2 answers

2

According to your Json, it is an object that contains several objects, in this case usd and eur :

  

{ "usd" : {"code": "USD", "alphaCode": "USD", "numericCode": "840", "name": "U.S.        Dollar "," rate ": 0.062953567779141," date ":" Sun, 4 Dec 2016 12:00:01        GMT "},

     

"eur" : {"code": "EUR", "alphaCode": "EUR", "numericCode": "978", "name": "Euro", "rate" : 0.059052814030065, "date": "Sun,        4 Dec 2016 12:00:01 GMT "}
  }

What you need is to obtain the objects inside an object, which you can do by obtaining the keys and using an Iterator to obtain their data:

String valorName="";
String valorRate="";

   try {
            //    contenidoJson es tu string conteniendo el json.
            JSONObject mainObject = new JSONObject(contenidoJson);
            //Obtenemos los objetos dentro del objeto principal.
            Iterator<String> keys = mainObject.keys();

            while (keys.hasNext())
            {
                // obtiene el nombre del objeto.
                String key = keys.next();
                Log.i("Parser", "objeto : " + key);
                JSONObject jsonObject = mainObject.getJSONObject(key);

                //obtiene valores dentro del objeto.
                valorName = jsonObject.getString("name");
                valorRate = jsonObject.getString("rate");

                //Imprimimos los valores.
                Log.i("Parser", valorName);
                Log.i("Parser", valorRate);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("Parser", e.getMessage());
        }

As a result you would get:

Parser: objeto : usd
Parser: U.S. Dollar
Parser: 0.062953567779141
Parser: objeto : eur
Parser: Euro
Parser: 0.059052814030065
    
answered by 04.12.2016 / 17:40
source
-2

If you use Gson, what you can do is create an object that has the name and type of instance variables something equivalent to what you have in the json and then you can deserialize it using the methods provided by gson aca explain very well how to do it. I hope I have helped you

    
answered by 04.12.2016 в 18:09