Pregunta

Decidí que quería intentar usar la API de Google Shopping la semana pasada, pero no tenía idea de cómo analizar los objetos JCON.

¡Después de buscar mucho aquí pude obtener la información del producto para un artículo! Sin embargo, no puedo reducir solo una cadena en el producto. Entonces, por ejemplo, solo quiero obtener el título de un producto.

Tengo lo siguiente:

jsonstring:

{
 "kind": "shopping#products",
 "etag": "\"GKsxsRlaBDslDpMe-MT1O7wqUDE/dMvQ5Pu2C806fWZJbNJ0GjdesJs\"",
 "id": "tag:google.com,2010:shopping/products",
 "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products?country=US&restrictBy=gtin:051500240908&startIndex=1&maxResults=25",
 "totalItems": 3,
 "startIndex": 1,
 "itemsPerPage": 25,
 "currentItemCount": 3,
 "items": [
  {
   "kind": "shopping#product",
   "id": "tag:google.com,2010:shopping/products/7585088/9884865157760252836",
   "selfLink": "https://www.googleapis.com/shopping/search/v1/public/products/7585088/gid/9884865157760252836",
   "product": {
    "googleId": "9884865157760252836",
    "author": {
     "name": "Southeastern Delivery",
     "accountId": "7585088"
    },
    "creationTime": "2011-07-25T00:15:58.000Z",
    "modificationTime": "2012-02-11T09:29:00.000Z",
    "country": "US",
    "language": "en",
    "title": "Jif Peanut Butter, Creamy",
    "description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
    "link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
    "brand": "Jif Peanut Butter",
    "condition": "new",
    "gtin": "00051500240908",
    "gtins": [
     "00051500240908"
    ],
    "inventories": [
     {
      "channel": "online",
      "availability": "inStock",
      "price": 15.64,
      "shipping": 1.56,
      "currency": "USD"
     }
    ],
    "images": [
     {
      "link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
     }
    ]
   }
  },
 ],
 "requestId": "0CLGzkcKVo64CFRDd5wod4mMAAA"
 }

Tengo el siguiente código en mi aplicación de Android para analizarlo:

try {

    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray itemsArray = jsonObject.getJSONArray("items");
    JSONObject productObject = itemsArray.getJSONObject(0);
    //String productTitle = productObject.getString("title");
    //tv.setText(productTitle);
    tv.setText(productObject.toString());
} catch (JSONException e) {
    // TODO Auto-generated catch block
    tv.setText("JSONOBJECT Error: " + e);
    e.printStackTrace();
}
setContentView(tv);

El TextView en mi aplicación Android ahora se mostrará (obviamente no sangrada, lo hice para leer fácilmente):

   "product": {
    "googleId": "9884865157760252836",
    "author": {
     "name": "Southeastern Delivery",
     "accountId": "7585088"
    },
    "creationTime": "2011-07-25T00:15:58.000Z",
    "modificationTime": "2012-02-11T09:29:00.000Z",
    "country": "US",
    "language": "en",
    "title": "Jif Peanut Butter, Creamy",
    "description": "Jif Creamy Peanut Butter. Fresh Roasted Peanut Taste. Look for the flavor seal. Contains no preservatives. No refrigeration required.",
    "link": "http://www.southeasterndelivery.com/Jif_Peanut_Butter_00051500240908/",
    "brand": "Jif Peanut Butter",
    "condition": "new",
    "gtin": "00051500240908",
    "gtins": [
     "00051500240908"
    ],
    "inventories": [
     {
      "channel": "online",
      "availability": "inStock",
      "price": 15.64,
      "shipping": 1.56,
      "currency": "USD"
     }
    ],
    "images": [
     {
      "link": "http://www.southeasterndelivery.com/images/ProductImages/00051500240908.jpg"
     }
    ]
   }

Ahora, si nota en mi código Java, tengo dos líneas comentadas. Si desencadeno esas líneas y luego comenta la línea:

tv.setText(productObject.toString());

La televisión se establece en este error: "Error de jsonobject: org.json.jsoneception: sin valor para el título". No estoy seguro de por qué esto es cierto porque claramente es un título en el ProductObject.

¡Cualquier ayuda sería genial!

¿Fue útil?

Solución

Le falta un nivel de información en su código. La matriz JSON contiene elementos, que contiene productos, que tienen un título.

Su código debería verse como:

JSONObject jsonObject = new JSONObject(jsonString); 
JSONArray itemsArray = jsonObject.getJSONArray("items"); 
JSONObject itemObject = itemsArray.getJSONObject(0); 
JSONObject productObject = itemObject.getJSONObject("product");
String productTitle = productObject.getString("title");

Otros consejos

Estoy usando martillo en mi proyecto. Es muy pequeño y muy rápido. Para convertir su JSON de Sting al uso real del objeto JSONObjet json = (JSONObject)JSONValue.parse(rawString);

Cuando tienes JSONObject lo tratas como un mapa. Asi que String title = (String) json.get("title")

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top