Showing posts with label gson. Show all posts
Showing posts with label gson. Show all posts

Saturday, February 9, 2013

Url encode an HTTP GET Solr request and parse json using gson java library

Make a request to the SOLR webserver and parse the json string to Java classes using the code snippets below.
The JSON to be parsed-
{
"responseHeader": {
"status": 0,
"QTime": 1,
"params": {
"q": "searchterm1 OR searchterm2",
"q.op": "AND",
"wt": "json",
"rows": "10000",
"version": "2.2"
}
},
"response": {
"numFound": 2,
"start": 0,
"docs": [
{
"name": "searchterm1",
"id": "1"
},
{
"name": "searchterm2",
"id": "2"
}
]
}
}
view raw Solr.json hosted with ❤ by GitHub
The corresponding Java classes-
public class Documents {
private String name;
private String id;
@Override
public String toString() {
return id+":"+name;
}
public String getName() {
return name;
}
public String getID() {
return id;
}
}
public class Results {
private String numFound;
private ArrayList<Documents> docs;
@Override
public String toString() {
return numFound +" - " + docs.toString();
}
public ArrayList<Documents> getDocs(){
return docs;
}
public String getNumFound() {
return numFound;
}
}
public class Response {
private Results response;
@Override
public String toString() {
return response.toString();
}
}
view raw Classes.java hosted with ❤ by GitHub
Code snippet to make a web server call and parse using gson-
String REQUEST_URL = "properties/select/?q=" + criteria
+ "&q.op=AND&rows=10&version=2.2&wt=json";
try {
URL url = new URL(webServer + "properties/select/?q="
+ URLEncoder.encode(criteria, "UTF-8")
+ "&q.op=AND&rows=10&version=2.2&wt=json");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
jsonString = inputLine;
}
in.close();
//Create gson
Gson gson = new GsonBuilder().create();
Response r = gson.fromJson(jsonString, Response.class);
LOG.info("MyGSON:" + r.toString());
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
view raw ParseGson.java hosted with ❤ by GitHub


The Java classes must have the same variable names as the Json's keys. Notice how nested Json elements are handled.