Sending Complex JSON Object - java

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));
}
};

Related

Getting a JSON Object from a JSON Array isn't working

I am trying to get JSON data from a JSON array which looks like this:
{
"common": [
{
"food_name": "eggs",
"serving_unit": "large",
"tag_name": "raw eggs",
"serving_qty": 1,
"common_type": null,
"tag_id": "775",
"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/775_thumb.jpg"
},
"locale": "en_US"
},
Here's what I am using:
public class GetDietData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String calories = "UNDEFINED";
try {
URL urlForGetRequest = new URL("https://trackapi.nutritionix.com/v2/search/instant?query=egg");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("x-app-key", "REMOVED");
connection.addRequestProperty("x-app-id", "REMOVED");
InputStream stream = new BufferedInputStream(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject();
JSONArray common = jsonRes.getJSONArray("common");
for (int i=0; i<common.length(); i++)
{
JSONObject jsonObj = common.getJSONObject(i);
calories = jsonObj.getString("food_name");
}
connection.disconnect();
} catch (IOException | JSONException e) {
editText=(findViewById(R.id.editTextDiet));
e.printStackTrace();
}
return calories;
}
#Override
protected void onPostExecute(String calories) {
if (calories == "UNDEFINED") {
Toast.makeText(Diet.this, "Food not found", Toast.LENGTH_LONG).show();
} else {
editText=(findViewById(R.id.editTextDiet));
editText.setText(calories);
}
}
}
I have the following problem:
W/System.err: org.json.JSONException: No value for common
at org.json.JSONObject.get(JSONObject.java:392)
So the problem seems to be that the "common" array has no value, hence it cannot find it's length? I'm unsure as to why it cannot see the "common" array as i have looked at numerous other questions about getting Objects from Arrays and I have replicated the code identically each time but with the same result. If I use solely a JSONObject and ignore the full array I can see in the stacktrace that it is attempting to download the whole array into that object which means it's definitely not something wrong with the GET request or the API keys.
Thanks.
the error you are getting is because you aren't passing the String response to jsonObject so it can't find any thing in an empty object
the fix is
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");

Post Request returning error 400 with Java

I don't really see where is my mistake in my java code.
I have to log in to Kofax Total Agility using REST API. For this I tried to use postman to test if my json was correctly built. Here is my login JSON :
{
"userIdentityWithPassword": {
"LogOnProtocol": "7",
"UnconditionalLogOn": false,
"UserId": "myLogin",
"Password": "myPassword"
}
}
I obtain a positive answer :
{
"d": {
"__type": "Session2:http://www.kofax.com/agility/services/sdk",
"SessionId": "1DE6B79F34054D58AEE1509FE583811F",
"ResourceId": "873C0F5C8BD34BAFBF4B14FF538FBAEC",
"DisplayName": "Aurore Mouret",
"IsValid": true,
"LogonState": {
"__type": "LogonState:http://www.kofax.com/agility/services/sdk",
"FormName": "",
"LogonStateType": 0
},
"ReserveLicenseUsed": false
}
}
So far, so good. For this I created models :
public class UserIdentityWithPasswordRestRequestModel {
LogOnWithPassword2RestRequestModel userIdentityWithPassword;
}
public class LogOnWithPassword2RestRequestModel {
#SerializedName("LogOnProtocol")
private String logOnProtocol;
#SerializedName("UnconditionalLogOn")
private boolean unconditionalLogOn;
#SerializedName("UserId")
private String userId; // C640521793431F4486D4EF1586672385
#SerializedName("Password")
private String password; // 123456
}
For the response :
public class LogOnWithPassword2RestResponseModel {
private DRestResponseModel d;
}
public class DRestResponseModel {
#SerializedName("__type")
private String type;
#SerializedName("SessionId")
private String sessionId;
#SerializedName("ResourceId")
private String resourceId;
#SerializedName("DisplayName")
private String displayName;
#SerializedName("IsValid")
private boolean isValid;
#SerializedName("LogonState")
private LogonStateRestResponseModel logonState;
#SerializedName("ReserveLicenseUsed")
private boolean reserveLicenseUsed;
}
public class LogonStateRestResponseModel {
#SerializedName("__type")
private String type;
#SerializedName("FormName")
private String formName;
#SerializedName("LogonStateType")
private String logonStateType;
}
Those classes should allow me to build the json.
Now I created a method that build the request object and expect a reponse object.
public LogOnWithPassword2RestResponseModel logOnWithPassword() throws Exception {
LogOnWithPassword2RestResponseModel returnValue = new LogOnWithPassword2RestResponseModel();
// set the HTTP Connection to the KTA Application
URL url = new URL("http://localhost/TotalAgility/Services/SDK/UserService.svc/json/LogOnWithPassword2");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setDoOutput(true);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
LogOnWithPassword2RestRequestModel userIdentityWithPassword = new LogOnWithPassword2RestRequestModel();
// set the values
userIdentityWithPassword.setLogOnProtocol(logOnProtocol);
userIdentityWithPassword.setUnconditionalLogOn(unconditionalLogOn);
userIdentityWithPassword.setUserId(userId);
userIdentityWithPassword.setPassword(password);
UserIdentityWithPasswordRestRequestModel userIdentityWithPasswordRestRequestModel =
new UserIdentityWithPasswordRestRequestModel();
userIdentityWithPasswordRestRequestModel.setUserIdentityWithPassword(userIdentityWithPassword);
// Convert to Json :
String jsonInputString = gson.toJson(userIdentityWithPasswordRestRequestModel);
System.out.println(jsonInputString);
// add request parameter, form parameters
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
System.out.println("OS " + os);
}
// get the response from KTA
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
returnValue = gson.fromJson(response.toString(), LogOnWithPassword2RestResponseModel.class);
System.out.println(returnValue);
}
return returnValue;
}
When i call this part of code, I note that I build the "right" JSON :
{
"userIdentityWithPassword": {
"LogOnProtocol": "7",
"UnconditionalLogOn": false,
"UserId": "myLogin",
"Password": "myPassword"
}
}
For a reason I can't explain, I obtain an error 400.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: http://94.247.28.163/TotalAgility/Services/SDK/UserService.svc/json/LogOnWithPassword2
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
at com.signature.app.ui.controller.DocumentController.logOnWithPassword(DocumentController.java:71)
at com.signature.app.Main.main(Main.java:21)
The line 71 is corresponding to this line of the try catch
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)))
I replaced
con.setRequestProperty("Content-Type", "application/json; utf-8");
With this code :
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");

how to post data in key/value pair? [duplicate]

This question already has answers here:
Java - sending HTTP parameters via POST method easily
(18 answers)
Closed 5 years ago.
i need to post data to particular url
in which in content i need to post html in content array and in meta headers in json format.
URL oracle = new URL("");
try (BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()))) {
String inputLine1;
while ((inputLine1 = in.readLine()) != null) {
System.out.println(inputLine1);
com.eclipsesource.json.JsonObject object = Json.parse(inputLine1).asObject();
com.eclipsesource.json.JsonArray items = Json.parse(inputLine1).asObject().get("data").asArray();
for (JsonValue item : items) {
//System.out.println(item.toString());
String name = item.asObject().getString("id", "Unknown Item");
System.out.println(name);
String quantity = item.asObject().getString("url", "id");
// JSONArray jsonArray2 = new JSONArray(quantity);
System.out.println(quantity);
/* Platform.runLater(() ->{
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(HV1.class.getName()).log(Level.SEVERE, null, ex);
}*/
Img.load(quantity);
URL url;
InputStream is = null;
BufferedReader br;
String line;
url = new URL(quantity);
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
byte[] postData= line.getBytes( StandardCharsets.UTF_8 );
wb2.load(line);
String originalUrl = "";
String newUrl = originalUrl.replace("ID", name);
System.out.println(newUrl);
String request = newUrl;
URL url1 = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url1.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "text/plain");
conn.setRequestProperty( "charset", "utf-8");
//conn.setRequestProperty( "Content-Length", Integer.toString( line ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write(postData);
System.out.println("200 ok");
this is what i tried but i had post in text/plain but i want to post in key/value pair.
updated code
URL oracle = new URL("");
try (BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()))) {
String inputLine1;
while ((inputLine1 = in.readLine()) != null) {
System.out.println(inputLine1);
com.eclipsesource.json.JsonObject object = Json.parse(inputLine1).asObject();
com.eclipsesource.json.JsonArray items = Json.parse(inputLine1).asObject().get("data").asArray();
for (JsonValue item : items) {
//System.out.println(item.toString());
String name = item.asObject().getString("id", "Unknown Item");
System.out.println(name);
String quantity = item.asObject().getString("url", "id");
// JSONArray jsonArray2 = new JSONArray(quantity);
System.out.println(quantity);
/* Platform.runLater(() ->{
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(HV1.class.getName()).log(Level.SEVERE, null, ex);
}*/
Img.load(quantity);
URL url;
InputStream is = null;
BufferedReader br;
String line;
url = new URL(quantity);
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
byte[] postData= line.getBytes( StandardCharsets.UTF_8 );
wb2.load(line);
String originalUrl = "";
String newUrl = originalUrl.replace("ID", name);
System.out.println(newUrl);
URL url1 = new URL(newUrl);
Map<String,Object> params = new LinkedHashMap<>();
params.put("content", postData);
params.put("meta", "abc");
StringBuilder postData1 = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData1.length() != 0) postData1.append('&');
postData1.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData1.append('=');
postData1.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData1.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url1.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in1 = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in1.read()) >= 0;)
System.out.print((char)c);
/* try{
Thread.sleep(400);
}catch(InterruptedException e){System.out.println(e);} */
}
}
}
this is my updted code(answer) this is how i solve my problem thanks for your precious time.
Take a look at this previous answer regarding HTTP Post parameters that exploit BasicNameValuePairs.
Name Value Pairs
Here is a pertinent piece of code from that answer.
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httppost = new HttpPost("your login link");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
Best would be using something like Spring and Jackson to create a JSON sending via a request, if you are not familiar with what you are trying to achieve:
This is just basic implementation
private final String uri = "yoururl.de/asdfasd";
private final HttpMethod httpMethod = HttpMethod.POST;
private final ContentType contentType = ContentType.json;
And EPO to transfer the Data
SendKeyValuePairsEPO implements Serializable{
private static final long serialVersionUID = 5311348008314829094L;
private final Integer startIndex;
private final Integer size;
private final Integer totalSize;
private final List<KeyValuePairEPO> values;
/**
* Contructor
*
* #param startIndex start searching index
* #param size requested result size
* #param totalSize total size of available records
* #param values the key value pairs
*/
public SendKeyValuePairsEPO(#JsonProperty("startIndex") final Integer startIndex,
#JsonProperty("size") final Integer size,
#JsonProperty("totalSize") final Integer totalSize,
#JsonProperty("values") final List<KeyValuePairEPO> values) {
this.startIndex = startIndex;
this.size = size;
this.totalSize = totalSize;
this.values = values;
}
and aswell a KeyValuePairEPO:
KeyValuePairEPO implements Serializable{
private static final long serialVersionUID = 5311348008314829094L;
private final String key;
private final String value;
private final String type; //maybe you need a type to tell what kind of value it is
...
And at last you will need to do something like:
/*package*/ <T> T sendRequest(Class<T> responseClass, Object requestEpo, String uri) {
try {
//Parse encapsulated COntent type to media type
HttpHeaders headers = new HttpHeaders();
MediaType requestContentType requestContentType = MediaType.APPLICATION_JSON;
//Set content type and accept header to this type
headers.setContentType(requestContentType);
headers.setAccept(Collections.singletonList(requestContentType));
//Parse the data object to a JSON
String requestJSONAsString = "";
if (request.getData() != null) {
try {
requestJSONAsString = RestObjectMapper.getInstance().writeValueAsString(requestEpo);
} catch (JsonProcessingException ex) {
throw new InternalServerErrorException(String.format("Error parsing: %s", requestEpo.getClass().getSimpleName()), ex);
}
}
//Perform the send request
return sendRequest(responseClass, uri, headers, httpMethod, requestJSONAsString);
} finally {
LOG.debug("Ended sendRequest");
}
}
private <T> T sendRequest(final Class<T> responseClass, final String uri, final HttpHeaders httpHeaders, final HttpMethod httpMethod, String requestJSON) {
try {
LOG.debug(String.format("Start sendRequest with:%s %s %s %s", uri, httpHeaders, httpMethod, requestJSON));
RestTemplate rest = new RestTemplate();
ClientHttpRequestFactory restFactory = rest.getRequestFactory();
if(restFactory instanceof SimpleClientHttpRequestFactory){
((SimpleClientHttpRequestFactory)restFactory).setReadTimeout(REQUEST_TIMEOUT);
((SimpleClientHttpRequestFactory)restFactory).setConnectTimeout(REQUEST_TIMEOUT);
}
HttpEntity<String> entity = new HttpEntity<>(requestJSON, httpHeaders);
final ResponseEntity<String> response = rest.exchange(uri, httpMethod, entity, String.class);
LOG.debug("Status:" + response.getStatusCode().toString());
String returnedPayload = response.getBody();
return RestObjectMapper.getInstance().readValue(returnedPayload, responseClass);
} catch (HttpStatusCodeException ex) {
LOG.error("HTTP Error in sendRequest: " + ex.getMessage());
switch (ex.getStatusCode()) {
case BAD_REQUEST:
throw new BadRequestException(uri, ex);
case NOT_FOUND:
throw new NotFoundException(uri, ex);
case FORBIDDEN:
throw new ForbiddenException(uri, ex);
case REQUEST_TIMEOUT:
throw new RequestTimeoutException(ex, REQUEST_TIMEOUT);
default:
throw new InternalServerErrorException(ex);
}
} catch (Exception ex) {
LOG.error("Error in sendRequest: " + ex.getMessage());
throw new InternalServerErrorException(ex);
} finally {
LOG.debug("Ended sendRequest");
}
}
where RestObjectMapper is:
public class RestObjectMapper extends ObjectMapper {
public static final String EMPTY_JSON = "{}";
private static final long serialVersionUID = 3924442982193452932L;
/**
* Singleton Instance
* Pattern: Initialization-on-demand holder idiom:
* <ul>
* <li>the class loader loads classes when they are first accessed (in this case Holder's only access is within the getInstance() method)</li>
* <li>when a class is loaded, and before anyone can use it, all static initializers are guaranteed to be executed (that's when Holder's static block fires)</li>
* <li>the class loader has its own synchronization built right in that make the above two points guaranteed to be threadsafe</li></ul>
*/
private static class INSTANCE_HOLDER {
private static final RestObjectMapper INSTANCE = new RestObjectMapper();
}
private RestObjectMapper() {
super();
configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
/**
* Gets the singleton Instance of the JSON Mapper
*
* #return the singleton instance
*/
public static RestObjectMapper getInstance() {
return INSTANCE_HOLDER.INSTANCE;
}
By the way ResponseClass is another EPO the result (JSON) will be mapped to.

get JSON object with API client

Im trying to get JSONobject from api but i cant get this piece of code to work.
I am new to android and java and JSON. i keep getting the error: in JSONobject cannot be applied
Main code:
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
List<CustomListView> contents = new ArrayList<CustomListView>();
try {
JSONObject row = result.getJSONObject(result**ERROR HERE**);
String content = row.optString("FormattedName");
String content2 = row.optString("Title");
String content3 = row.optString("Subtitle");
String content4 = row.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
} catch (JSONException e) {
e.printStackTrace();
}
Api client:
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
JSON output:
{
"FormattedName": "Home page | Footer grijs",
"Title": null,
"Subtitle": null,
"Text": "<div style=\"text-align: center;\"><img style=\"max-width: 80%;\" src=\"/MoxieManager/code.PNG\" alt=\"\"></div>",
"WebsiteId": "6869a7a1-0d65-4cfa-9df1-b0b0d346212e",
"Id": "b9906cb0-cdb2-484a-b603-020e8b64f97b",
"DateCreated": "2016-01-25T12:09:50.367",
"DateModified": "2016-02-11T08:51:54.223",
"CreatedBy": "Drie-O Automatisering",
"ModifiedBy": "Drie-O Automatisering",
"SortOrder": 0
}
Reason:
You are already getting the JSONObject from AsycnTask. There is no need of
JSONObject row = result.getJSONObject(result);
When you try to used this it means you are trying to find a object result inside object result. Which is not the case here.
Solution:
You should remove the above mentioned call and use result in these calls like below.
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
Is the error coming at this line?
JSONObject row = result.getJSONObject(result);
result is a JSONObject, and the method requires a String.
Why not try to convert result to String and pass it. Something like.
JSONObject resultJson = new JSONObject();
result.toString();
JSONObject row = result.getJSONObject(resultJson );
You have already got the JSON output as given from the APIClient.
JSONObject row = result.getJSONObject(result);
this line is redundant unless your real response is an array list enclosed object and you are getting only a row from it.
Directly you can access internal elements in main object now.

Array and Object JSON from URL Parsing

I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}
JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.
please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.
Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}
Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}
you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"

Categories