Cannot get single value from JSON using Jackson - java

I need to get a single value from JSON, but I get null as value.
public class PlaceTest {
public void sendRequest() throws Exception{
URIBuilder builder = new URIBuilder("https://maps.googleapis.com/maps/api/place/findplacefromtext/json");
builder.addParameter("key","mykey");
builder.addParameter("input","London");
builder.addParameter("inputtype","textquery");
HttpGet getReq = new HttpGet(builder.build());
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(getReq);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder builders = new StringBuilder();
String s;
while ((s = reader.readLine())!=null){
builders.append(s+"\n");
}
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(builders.toString());
JsonNode candidates = node.get("candidates");
System.out.println(candidates.get("place_id"));
//json
System.out.println(builders.toString());
}
}
The JSON code is:
{"candidates":[{"place_id" : "ChIJdd4hrwug2EcRmSrV3Vo6llI"}],"status" : "OK"}

In the above JSON candidates values is JsonArray
JsonNode node = mapper.readTree(builders.toString());
JsonNode candidates = node.get("candidates");
Now iterate the JsonArray and get place_id:
if (candidates.isArray()) {
for (JsonNode objNode : arrNode) {
System.out.println(objNode.get("place_id"));
}
}

Related

Post method in RestAssured throws java.net.ConnectException

I'm trying to Post a JSON to a Rest service using RestAssured and it throws java.net.ConnectException error.
Since my JSON message is complex, I've made it available within the txt file.
public class PPJson {
public static void main(String[] args) throws IOException, JSONException {
BufferedReader tempreader = new BufferedReader(new FileReader("/Users/RestService/Jsonfileinput.txt"));
StringBuilder sbuilder = new StringBuilder();
String line = tempreader.readLine();
while (line != null) {
sbuilder.append(line);
line = tempreader.readLine();
}
tempreader.close();
//Initializing Rest API's URL
String APIUrl = "http://api.sample.com/api/v3/parcel/collect?apiKey={Value}";
//Initializing payload or API body
String APIBody = sbuilder.toString();
// Building request using requestSpecBuilder
RequestSpecBuilder builder = new RequestSpecBuilder().setBody(APIBody).setContentType("application/json; charset=UTF-8");
RequestSpecification requestSpec = builder.build();
//Making post request with authentication
Response response = given().authentication().preemptive().basic("","").spec(requestSpec).when().post(APIUrl);
JSONObject JSONResponseBody = new JSONObject(response.body().asString());
//Fetching the desired value of a parameter
String result = JSONResponseBody.getString("status");
System.out.println(result);
}
}
#all, the issue has been fixed, removed the references to RequestSpecs and here's the code snippet
public class ParcelPointJson {
public static void main(String[] args) throws IOException, JSONException {
BufferedReader tempreader = new BufferedReader(new FileReader("/Users/srkrish/gitTrial/pim-automation/RestService/Jsonfileinput.txt"));
StringBuilder sbuilder = new StringBuilder();
String line = tempreader.readLine();
while (line != null) {
sbuilder.append(line);
line = tempreader.readLine();
}
tempreader.close();
//Initializing Rest API's URL
String APIUrl = "http://api.staging.wow.parcelpoint.com.au/api/v3/parcel/collect?apiKey=09BH1TXV";
//Initializing payload or API body
String APIBody = sbuilder.toString();
//Making post request with authentication
Response response = given().contentType("application/json; charset=UTF-8").body(APIBody).when().post(APIUrl);
JSONObject JSONResponseBody = new JSONObject(response.body().asString());
//Fetching the desired value of a parameter
String result = JSONResponseBody.getString("parcelId");
System.out.println(result);
//Assert.assertEquals(result, "200");
}
}

Json jackson : can't parse a json a file

I m trying to parse a JSON file and store it in an list. I m getting this error :
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
Here is my JSON file
{ "budgetList":[
{
"label":"Salary Tim",
"category":"Monthly Income",
"real":1590,
"estimated":1590,
"date":"",
"month":"",
"year":"",
"type":"Income"
},
{
"label":"Salary Tom",
"category":"Monthly Income",
"real":1540,
"estimated":1540,
"date":"",
"month":"",
"year":"",
"type":"Income"
}
]
}
Here is my code
Budget :
public class Budget {
private String label;
private String category;
private int real;
private int estimated;
private Date date;
private int year;
private String type;
....
....
}
My service :
List<Budget> budgets = objectMapper.readValue(new File("src/main/resources/json/new_exercise.json"), TypeFactory.defaultInstance().constructCollectionType(List.class,
Budget.class));
Where am I wrong?
Thanks in advance.
ANSWER FOUND
Code is
ObjectMapper objectMapper = new ObjectMapper();
List<Budget> budgets = null;
JsonNode node = objectMapper.readTree(new File("src/main/resources/json/new_exercise.json"));
node = node.get("budgetList");
TypeReference<List<Budget>> typeRef = new TypeReference<List<Budget>>(){};
budgets = objectMapper.readValue(node.traverse(), typeRef);
can you, use GSON library? Is very simple
Reader reader = new InputStreamReader(new
FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new
TypeToken>() {}.getType());
I think that the only problem is when Date and integer parser when is empty. but you can register adapters like:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch (ParseException e) {
return null;
}
}
});
Reader reader = new InputStreamReader(new
FileInputStream("/opt/file.json"));
Gson gson = gsonBuilder.create();
List listBudget = gson.fromJson(reader, new
TypeToken>() {}.getType());
It works for you?, and dont forget to validate you json. "

Convert InputStream into JSON

I am using json-rpc-1.0.jar.Below is my code. I need to convert InputStream object into JSON since the response is in JSON.
I did verify the json response obtained from Zappos API. It is valid.
PrintWriter out = resp.getWriter();
String jsonString = null;
URL url = new URL("http://api.zappos.com/Search?term=boots&key=my_key");
InputStream inputStream = url.openConnection().getInputStream();
resp.setContentType("application/json");
JSONSerializer jsonSerializer = new JSONSerializer();
try {
jsonString = jsonSerializer.toJSON(inputStream);
} catch (MarshallException e) {
e.printStackTrace();
}
out.print(jsonString);
I get the below mentioned exception:
com.metaparadigm.jsonrpc.MarshallException: can't marshall sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
at com.metaparadigm.jsonrpc.JSONSerializer.marshall(JSONSerializer.java:251)
at com.metaparadigm.jsonrpc.JSONSerializer.toJSON(JSONSerializer.java:259)
at Communicator.doGet(Communicator.java:33)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at filters.ExampleFilter.doFilter(ExampleFilter.java:149)
Make use of Jackson JSON parser.
Refer - Jackson Home
The only thing you need to do -
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = mapper.readValue(inputStream, Map.class);
Now jsonMap will contain the JSON.
ObjectMapper.readTree(InputStream) easily let's you get nested JSON with JsonNodes.
public void testMakeCall() throws IOException {
URL url = new URL("https://api.coindesk.com/v1/bpi/historical/close.json?start=2010-07-17&end=2018-07-03");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
InputStream is = httpcon.getInputStream();
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonMap = mapper.readTree(is);
JsonNode bpi = jsonMap.get("bpi");
JsonNode day1 = bpi.get("2010-07-18");
System.out.println(bpi.toString());
System.out.println(day1.toString());
} finally {
is.close();
}
}
Result:
{"2010-07-18":0.0858,"2010-07-19":0.0808,...}
0.0858
Better to save memory by having output as Stream<JsonNode>
private fun InputStream.toJsonNodeStream(): Stream<JsonNode> {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(this.toJsonNodeIterator(), Spliterator.ORDERED),
false
)
}
private fun InputStream.toJsonNodeIterator(): Iterator<JsonNode> {
val jsonParser = objectMapper.factory.createParser(this)
return object: Iterator<JsonNode> {
override fun hasNext(): Boolean {
var token = jsonParser.nextToken()
while (token != null) {
if (token == JsonToken.START_OBJECT) {
return true
}
token = jsonParser.nextToken()
}
return false
}
override fun next(): JsonNode {
return jsonParser.readValueAsTree()
}
}
}

Converting json from a file to a java object

I am trying to convert json from a text file into a java object.
I have tried both the jackson library, I put in the dependency and what not. My json file has both camel case and underscores, and that is causing an error when running my program. Here is the code that I used for when relating to the gson librar and it does not do anything, the output is the same with or without the code that I placed.
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
try
{
BufferedReader br = new BufferedReader(new FileReader("/test.json"));
// convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);
System.out.println(obj);
} catch (IOException e)
{
e.printStackTrace();
}
Now I also tried the jackson library. Here is the code i used
java.net.URL url = this.getClass().getResource("/test.json");
File jsonFile = new File(url.getFile());
System.out.println("Full path of file: " + jsonFile);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
InputStream is = Test_Project.class.getResourceAsStream("/test.json");
SampleDto testObj = mapper.readValue(is, SampleDto.class);
System.out.println(testObj.getCreatedByUrl());
I am not sure what to do,
This simple example works like a charm:
DTOs
public class SampleDTO
{
private String name;
private InnerDTO inner;
// getters/setters
}
public class InnerDTO
{
private int number;
private String str;
// getters/setters
}
Gson
BufferedReader br = new BufferedReader(new FileReader("/tmp/test.json"));
SampleDTO sample = new Gson().fromJson(br, SampleDTO.class);
Jackson
InputStream inJson = SampleDTO.class.getResourceAsStream("/test.json");
SampleDTO sample = new ObjectMapper().readValue(inJson, SampleDTO.class);
JSON (test.json)
{
"name" : "Mike",
"inner": {
"number" : 5,
"str" : "Simple!"
}
}
public static void main(String args[]){
ObjectMapper mapper = new ObjectMapper();
/**
* Read object from file
*/
Person person = mapper.readValue(new File("/home/document/person.json"), Person.class);
System.out.println(person);
}
A common way of getting both array of json in file or simply json would be
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);
List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);
The file.json needs to be placed in the resources folder. If your file only has a json block without json array square brackets [] , you can skip the CollectionType
InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);
Also refer here for original question from where I have drawn.

Sending Complex JSON Object

I want to communicate with a web server and exchange JSON information.
my webservice URL looking like following format: http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus
Here is my JSON Request format.
{
"f": {
"Adults": 1,
"CabinClass": 0,
"ChildAge": [
7
],
"Children": 1,
"CustomerId": 0,
"CustomerType": 0,
"CustomerUserId": 81,
"DepartureDate": "/Date(1358965800000+0530)/",
"DepartureDateGap": 0,
"Infants": 1,
"IsPackageUpsell": false,
"JourneyType": 2,
"PreferredCurrency": "INR",
"ReturnDate": "/Date(1359138600000+0530)/",
"ReturnDateGap": 0,
"SearchOption": 1
},
"fsc": "0"
}
I tried with the following code to send a request:
public class Fdetails {
private String Adults = "1";
private String CabinClass = "0";
private String[] ChildAge = { "7" };
private String Children = "1";
private String CustomerId = "0";
private String CustomerType = "0";
private String CustomerUserId = "0";
private Date DepartureDate = new Date();
private String DepartureDateGap = "0";
private String Infants = "1";
private String IsPackageUpsell = "false";
private String JourneyType = "1";
private String PreferredCurrency = "MYR";
private String ReturnDate = "";
private String ReturnDateGap = "0";
private String SearchOption = "1";
}
public class Fpack {
private Fdetails f = new Fdetails();
private String fsc = "0";
}
Then using Gson I create the JSON object like:
public static String getJSONString(String url) {
String jsonResponse = null;
String jsonReq = null;
Fpack fReq = new Fpack();
try {
Gson gson = new Gson();
jsonReq = gson.toJson(fReq);
JSONObject json = new JSONObject(jsonReq);
JSONObject jsonObjRecv = HttpClient.SendHttpPost(url, json);
jsonResponse = jsonObjRecv.toString();
}
catch (JSONException e) {
e.printStackTrace();
}
return jsonResponse;
}
and my HttpClient.SendHttpPost method is
public static JSONObject SendHttpPost(String URL, JSONObject json) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(json.toString());
httpPostRequest.setEntity(se);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
// Transform the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
return jsonObjRecv;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Now I get the following exception:
org.json.JSONException: Value !DOCTYPE of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
and the printout of JSON string right before I make the request is as follows:
{
"f": {
"PreferredCurrency": "MYR",
"ReturnDate": "",
"ChildAge": [
7
],
"DepartureDate": "Mar 2, 2013 1:17:06 PM",
"CustomerUserId": 0,
"CustomerType": 0,
"CustomerId": 0,
"Children": 1,
"DepartureDateGap": 0,
"Infants": 1,
"IsPackageUpsell": false,
"JourneyType": 1,
"CabinClass": 0,
"Adults": 1,
"ReturnDateGap": 0,
"SearchOption": 1
},
"fsc": "0"
}
How do I solve this exception? Thanks in advance!
To create a request with JSON object attached to it what you should do is the following:
public static String sendComment (String commentString, int taskId, String sessionId, int displayType, String url) throws Exception
{
Map<String, Object> jsonValues = new HashMap<String, Object>();
jsonValues.put("sessionID", sessionId);
jsonValues.put("NewTaskComment", commentString);
jsonValues.put("TaskID" , taskId);
jsonValues.put("DisplayType" , displayType);
JSONObject json = new JSONObject(jsonValues);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url + SEND_COMMENT_ACTION);
AbstractHttpEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
return getContent(response);
}
I'm not quite familiar with Json, but I know it's pretty commonly used today, and your code seems no problem.
How to convert this JSON string to JSON object?
Well, you almost get there, just send the JSON string to your server, and use Gson again in your server:
Gson gson = new Gson();
Fpack f = gson.fromJSON(json, Fpack.class);
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html
About the Exception:
You should remove this line, because you are sending a request, not responsing to one:
httpPostRequest.setHeader("Accept", "application/json");
And I would change this line:
httpPostRequest.setHeader("Content-type", "application/json");
to
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
If this doesn't make any difference, please print out your JSON string before you send the request, let's see what's in there.
From what I have understood you want to make a request to the server using the JSON you have created, you can do something like this:
URL url;
HttpURLConnection connection = null;
String urlParameters ="json="+ jsonSend;
try {
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
Actually it was a BAD REQUEST. Thats why server returns response as XML format.
The problem is to convert the non primitive data(DATE) to JSON object.. so it would be Bad Request..
I solved myself to understand the GSON adapters.. Here is the code I used:
try {
JsonSerializer<Date> ser = new JsonSerializer<Date>() {
#Override
public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext comtext) {
return src == null ? null : new JsonPrimitive("/Date("+src.getTime()+"+05300)/");
}
};
JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
#Override
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext jsonContext) throws JsonParseException {
String tmpDate = json.getAsString();
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(tmpDate);
boolean found = false;
while (matcher.find() && !found) {
found = true;
tmpDate = matcher.group();
}
return json == null ? null : new Date(Long.parseLong(tmpDate));
}
};

Categories