Problema para convertir JSON a clase en Java (búsqueda personalizada de Google)
-
22-10-2019 - |
Pregunta
Soy muy nuevo en JSON, Google API. Así que por favor guía.
Estoy tratando de escribir una aplicación en 'Java' que utilizaría la API de Google Custom Servch a través de Restful. Empecé a aprender JSON y pasando por [enlace http://code.google.com/apis/customsearch/v1/overview.html Quería escribir algún código.
Esto muestra el JSON de la búsqueda de Google:
http://code.google.com/apis/customsearch/v1/reference.html#method_search_cse_list
la referencia es http://code.google.com/apis/customsearch/v1/reference.html
Desde la referencia que encontré qué campos de esta investigación aduanera serían String o INT o cualquier otro tipo de datos. También han definido la estructura de cada objeto.
Pero estoy enfrentando problemas con algunos tipos de datos:
items.title array The title of the search result, in plain text.
items.snippet array The snippet of the search result, in plain text.
items.pagemap object Contains pagemap information for this search result.
items.pagemap.value array Pagemap information, keyed by the name of this pagemap.
items.pagemap.value.value object The actual pagemap information.
¿Cómo los definiría en mi clase? ¿Qué tipo de matriz es Title String o Char y este PaGEMap es alguna convención o cualquier sitio puede dar sus propias etiquetas?
// clase CustomSearch
public class CustomSearch {
public URL getURL() throws MalformedURLException{
return url.getURL();
}
@Key ("items") ArrayList<SearchResult> results;
private @Key SearchURL url;
private @Key Query queries;
}
// clase
class SearchResult {
public SearchResult(){
}
public String getTitle(){
return title;
}
public String getLink(){
return link;
}
public String getSnippet(){
return snippet;
}
private @Key String title; // is this right ?
private @Key String htmlTitle;
private @Key String link;
private @Key String snippet; // is this right ?
private @Key String htmlSnippet;
}
Solución
Emití una búsqueda real usando mi clave como se sugiere en el ejemplo de Google:
GET https://www.googleapis.com/customsearch/v1?key=INSERT-YOUR-KEY&cx=013036536707430787589:_pqjad5hr1a&q=flowers&alt=json
Y esto es lo que obtengo (mostrando solo un poco de datos)
items": [ { "kind": "customsearch#result", "title": "FTD.COM - Flowers Online | Roses, Fresh Flowers, Plants and Gift ...", "htmlTitle": "FTD.COM - \u003cb\u003eFlowers\u003c/b\u003e Online | Roses, Fresh \u003cb\u003eFlowers\u003c/b\u003e, Plants and Gift \u003cb\u003e...\u003c/b\u003e", "link": "http://www.ftd.com/", "displayLink": "www.ftd.com", "snippet": "Aug 2, 2011 ... Order flowers online for same day floral delivery. Shop for flowers, chocolates, roses, gifts and gift baskets by occasion, season or get beautiful ...", "htmlSnippet": "Aug 2, 2011 \u003cb\u003e...\u003c/b\u003e Order \u003cb\u003eflowers\u003c/b\u003e online for same day floral delivery. Shop for \u003cb\u003eflowers\u003c/b\u003e, chocolates, \u003cbr\u003e roses, gifts and gift baskets by occasion, season or get beautiful \u003cb\u003e...\u003c/b\u003e", "cacheId": "D_MQAIEeVpAJ", "pagemap": { "metatags": [ { "y_key": "e887dc108fef83f6", "msvalidate.01": "71957E1C9D33211154243270EB14C63C" } ] } ......
Parece que:
items.title array The title of the search result, in plain text.
Esto parece un tipo de datos de cadena de un montón de resultados que obtengo, por lo que no estoy seguro de por qué la referencia lo clasificó como una matriz
items.snippet array The snippet of the search result, in plain text.
Esto también parece un tipo de datos de cadena de los resultados que obtuve
items.pagemap object Contains pagemap information for this search result. items.pagemap.value array Pagemap information, keyed by the name of this pagemap. items.pagemap.value.value object The actual pagemap information.
Basado en el Descripción de la pagma Esto parece un arbitrary Key-Value Data que el sitio web podría proporcionar.
A continuación se muestran algunos de los pagumaps que obtengo de mi prueba para su referencia:
"pagemap": { "metatags": [ { "y_key": "e887dc108fef83f6", "msvalidate.01": "71957E1C9D33211154243270EB14C63C" } ] } "pagemap": { "website": [ { "type": "website", "title": "ProFlowers", "description": "The freshest flowers, guaranteed to last at least 7 days.", "image": "http://a1128.g.akamai.net/7/1128/497/0001/images.proflowers.com/pcsite/ProflowersLogo_nb.gif", "url": "http://www.proflowers.com/", "site_name": "ProFlowers", "app_id": "180475245301608" } ], "metatags": [ { "msnbot": "NOODP", "msvalidate.01": "77940E049C181974C3AA656C72688B4C" } ] } "pagemap": { "metatags": [ { "viewport": "width=device-width; initial-scale=1.0; maximum-scale=1.0;" } ]
Como Pagemap no está estructurado, los almacenaría como Map<String, JSONObject> pagemap
. Como puede ver, solo mantengo el JsonObject original en Pagemap para que si lo necesita, siempre puede extraerlo. A menos que haya un conjunto de definiciones, qué tipo podríamos poner en PagEmap junto con sus campos, lo que representa el valor del pageMap como clase podría ser difícil.