I need to convert the following Json code into Java.
{
"service": {
"type": "nyd",
"discount": 0.20,
"items": [
{
"asin": "....",
"link": "http://amazon.com/.....",
"quantity": 2
},
// ...
],
// See /addresses
"shipping_address": {
"full_name": "Mr Smith",
"street1": "Some Mission St",
"street2": "", // Optional
"city": "San Francisco",
"state": "CA",
"zip": "94000",
"country": "US",
"phone": "1234567890"
}
}
}
I'm currently implementing this by using the following code:
String postUrl = "https://API.example.com";
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost(postUrl);
StringEntity postingString = new StringEntity("{\"service\" : {\"type\":\"nnn\", \"discount\":" + 0.2 + ",\"items\" : [ { \"asin\":\"B018Y1XXT6\", \"link\":\"https://www.amazon.com/Yubico-Y-159-YubiKey-4-Nano/dp/B018Y1XXT6/\", \"quantity\":" + 1 + " } ], \"shipping_address\" : {\"full_name\":\"Steven Smith\", \"street1\":\"11 Man Rd\", \"street2\":\"\", \"city\":\"Woonsocket\", \"state\":\"RI\", \"zip\":\"02844\", \"country\":\"US\", \"phone\":\"7746536483\" } } } ");
Mote: the values are different but I'm trying to achieve the same syntax.
System.out.println("Post String value: " + IOUtils.toString(postingString.getContent()));
httpPostRequest.addHeader("Authorization", "Token " + apiKey);
httpPostRequest.setEntity(postingString);
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.addHeader("content-type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(httpPostRequest);
System.out.println(response.toString());
The "postString" value is:
{"service" : {"type":"nnn", "discount":0.2,"items" : [ { "asin":"B018Y1XXT6", "link":"https://www.amazon.com/Yubico-Y-159-YubiKey-4-Nano/dp/B018Y1XXT6/", "quantity":1 } ], "shipping_address" : {"full_name":"Steven Smith", "street1":"11 Man Rd", "street2":"", "city":"Woonsocket", "state":"RI", "zip":"02844", "country":"US", "phone":"17746536483" } } }
However, when I attempt to submit the request I get a Bad Request error.
How can I format the String correctly?
Thanks
You have sent an incorrect json String if you want to go with the json provided .Following are the errors:
1) "service = {\"type\" should be {\"service\" : {\"type
2) discount should not be a string
\"discount\":\"0.2\", should be \"discount\":" + 0.2 + ",
3) items = [ should be \"items\" : [
4) quantity should not be string
\"quantity\":\"1\" } should be \"quantity\":" + 1 + "}
5) comma missing before shipping address key
] shipping_address = should be ], \"shipping_address\" :
6) add one more } at the end
Related
I am using RESTAssured java library in Selenium for API test automation. I need to pass a json string as a value to one parameter of a POST request body. My request body looks like this:
{
"parameter1": "abc",
"parameter2": "def",
"parameter3": {
"id": "",
"key1": "test123",
"prod1": {
"id": "",
"key3": "test123",
"key4": "12334",
"key5": "3",
"key6": "234334"
},
"prod2": {
"id": "",
"key7": "test234",
"key8": "1",
"key9": true
}
},
"parameter4": false,
"parameter5": "ghi"
}
For parameter3 I need to be pass a string value in json format. The json file is located in my local system and is a huge file, so it would make sense if I can pass the path to the json file.
Is there any way using RestAssured to achieve this?
Use org.json library;
Read json file and get as a String
String content = "";
try {
content = new String(Files.readAllBytes(Paths.get("absolute_path_to_file\\example.json")));
} catch (IOException e) {
e.printStackTrace();
}
Covert the String to JSONObject
JSONObject jsonObject = new JSONObject(content);
Get the new json object that you need to put in the jsonObject
String jsonString = "{\n" +
" \"firstName\": \"John\",\n" +
" \"lastName\" : \"doe\",\n" +
" \"age\" : 26,\n" +
" \"address\" : {\n" +
" \"streetAddress\": \"naist street\",\n" +
" \"city\" : \"Nara\",\n" +
" \"postalCode\" : \"630-0192\"\n" +
" }\n" +
"}";
JSONObject updateObject = new JSONObject(jsonString);
Replace the value of parameter3 with new updateObject
jsonObject.put("parameter3", updateObject);
System.out.println(jsonObject.toString());
If you beautify the printed output;
{
"parameter5": "ghi",
"parameter4": false,
"parameter3": {
"firstName": "John",
"lastName": "doe",
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"age": 26
},
"parameter2": "def",
"parameter1": "abc"
}
If you want to update a nested json object like prod1 in parameter3
JSONObject parameter3JsonObject = jsonObject.getJSONObject("parameter3");
parameter3JsonObject.put("prod1", updateObject);
I'm attempting to list an item on EBay using EBay's Inventory API via the following code (I'm using Apache HTTP Client):
public void put() throws ClientProtocolException, IOException
{
String url = "https://api.ebay.com/sell/inventory/v1/inventory_item/83368339";
String charset = "utf-8";
HttpClient client = HttpClientBuilder.create().build();
HttpPut put = new HttpPut(url);
// add request header
put.addHeader("Authorization", "Bearer <TOKEN>");
put.addHeader("Content-Language", "en-US");
String json = "{ \"availability\": { \"pickupAtLocationAvailability\": [ { \"availabilityType\": \"IN_STOCK\", \"fulfillmentTime\": { \"unit\": \"TimeDurationUnitEnum\": \"BUSINESS_DAY\", \"value\": 1 }, \"merchantLocationKey\": \"NJ\", \"quantity\": 1 } ], \"shipToLocationAvailability\": { \"quantity\": 1 } }, \"condition\": \"ConditionEnum : [NEW]\", \"conditionDescription\": \"New condition\","
+ "\"product\": { \"aspects\": \"object\", \"brand\": \"Outlite\", \"description\": \"ADJUSTABLE FOCUS: Intense Spotlight for long range observation can up to 600 feet, Circle Floodlight for large area illumination\", \"imageUrls\": [ \"https://images-na.ssl-images-amazon.com/images/I/71c57aJiDAL._SL1500_.jpg\" ], \"title\": \"Outlite A100 Portable Ultra Bright Handheld LED Flashlight\", \"sku\": \"sku546372817\" }";
HttpResponse response = client.execute(put);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
}
However I'm encountering the following error:
Response Code : 400
{"errors":[{"errorId":2004,"domain":"ACCESS","category":"REQUEST","message":"Invalid request","longMessage":"The request has errors. For help, see the documentation for this API.","parameters":[{"name":"reason","value":"Could not serialize field [availability.pickupAtLocationAvailability.availabilityType]"}]}]}
From the comments above, there were a few issues:
Remove the surrounding parentheses
Remove the surrounding quotes around the JSON
Enum formatting
After the last comment and confirming that removing the square brackets might have cleared up the availabilityType enum issue, here's what I think your final JSON should look like:
String json = "{ \"availability\": { \"pickupAtLocationAvailability\": [ { \"availabilityType\": \"IN_STOCK\", \"fulfillmentTime\": { \"unit\": \"BUSINESS_DAY\", \"value\": 1 }, \"merchantLocationKey\": \"NJ\", \"quantity\": 1 } ], \"shipToLocationAvailability\": { \"quantity\": 1 } }, \"condition\": \"NEW\", \"conditionDescription\": \"New condition\","
+ "\"product\": { \"aspects\": \"object\", \"brand\": \"Outlite\", \"description\": \"ADJUSTABLE FOCUS: Intense Spotlight for long range observation can up to 600 feet, Circle Floodlight for large area illumination\", \"imageUrls\": [ \"https://images-na.ssl-images-amazon.com/images/I/71c57aJiDAL._SL1500_.jpg\" ], \"title\": \"Outlite A100 Portable Ultra Bright Handheld LED Flashlight\", \"sku\": \"sku546372817\" }}";
Here it is split out into non-Java escapedness:
{
"availability": {
"pickupAtLocationAvailability": [{
"availabilityType": "IN_STOCK",
"fulfillmentTime": {
"unit": "BUSINESS_DAY",
"value": 1
},
"merchantLocationKey": "NJ",
"quantity": 1
}],
"shipToLocationAvailability": {
"quantity": 1
}
},
"condition": "NEW",
"conditionDescription": "New condition",
"product": {
"aspects": "object",
"brand": "Outlite",
"description": "ADJUSTABLE FOCUS: Intense Spotlight for long range observation can up to 600 feet, Circle Floodlight for large area illumination",
"imageUrls": ["https://images-na.ssl-images-amazon.com/images/I/71c57aJiDAL._SL1500_.jpg"],
"title": "Outlite A100 Portable Ultra Bright Handheld LED Flashlight",
"sku": "sku546372817"
}
}
I modified the fulfillmentTime.unit and condition enums as well. It also looks like you might've been missing an a closing curly bracket at the end, so I added that as well.
I am working on a project with a SonicWall router. The responses that I get from it are in json format. I have no problems parsing them etc, etc but it seems that there is one case where the SW will return an invalid json as a response. Here is an example:
{
"success": false,
"reboot_required": false,
"status": [
{
"cli": [
{ "command": [ { "token": "no" }, { "token": "nat-policy" }, { "token": "id", "error": true }, { "token": "10", "error": true } ] },
{ "command": [ { "token": "end" } ] }
],
"info": [
{ "type": "error", "code": "CLI_E_NOT_FOUND", "message": "Nat Policy not found.
" }
]
}
]
}
Notice that the message does not close properly but changes a line? This causes the following parsingException:
Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 13 at (line no=11, column no=97, offset=447)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:532)
at org.glassfish.json.JsonTokenizer.readString(JsonTokenizer.java:189)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:376)
at org.glassfish.json.JsonParserImpl$ObjectContext.getNextEvent(JsonParserImpl.java:261)
at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:172)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:149)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:177)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:143)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:180)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:143)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:180)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:103)
Is there any way to turn this in a valid json?
Get the json response and replace all new lines first before parsing it to object.
response.replaceAll("\r?\n", "");
Sample code using GSON API
String json = "{\"msg\" : \"Hello \n World\"}";
System.out.println(json);
json = json.replaceAll("\r?\n", "");
Map<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>(){}.getType());
System.out.println("Actual message:" + map.get("msg"));
Output:
{"msg" : " Hello
World"}
Actual message: Hello World
I have encountered a problem whilst developing my Android application. My problem is that I don't know how to parse JSON code from an URL using GSON. I searched Google and SO for about an hour or so, but nothing worked for me. Everything I found on the internet referred to custom JSON code, not code from an URL. Here is a small sample of the data I have.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
I am a beginner at JSON/GSON so I need a bit of help. Here is what I have:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
// Convert to a JSON object to print data
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
I tried a loop to parse the array but that failed miserably. Any help regarding this problem is highly appreciated.
------------------------------EDIT-----------------------------------------------
I am extremely sorry about the incorrrect JSON code. I have updated the code but still cannot figure out the solution.
You JSON is wrong:
"date": "3 hours agp",
"distance": "1.9km"
}
{
"country": "Canada",
To coorect it, you must add a ,
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
Try this, using the basic org.json.JSONObject and org.json.JSONArray it works fine for me...
// This string is the JSON you gave as imput
String json = "{ \"status\": { \"error\": \"NO\", \"code\": 200, \"description\": \"none\", \"message\": \"Request ok\" }, \"geoLocation\": { \"city_id\": \"147\", \"city_long\": \"Saint-Laurent\", \"region_short\": \"QC\", \"region_long\": \"Quebec\", \"country_long\": \"Canada\", \"country_id\": \"43\", \"region_id\": \"35\" }, \"stations\": [ {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\" }, {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\" } ]}";
try{
JSONObject rootobj = new JSONObject(json);
JSONArray array = rootobj.getJSONArray("stations");
for( int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
String price = o.getString("price");
String address = o.getString("address");
//...
}
}catch(JSONException jse){
// Manage Exception here
}
Try below code to fetch data from url and parse the response using Gson.
Note : Remove "?callback=?" from your url, that will remove "?(" from your response
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";
URL u = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonElement element = new Gson().fromJson (br, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
JsonArray jArray = jsonObj.get("stations").getAsJsonArray();
for (int i = 0, size = jArray.length(); i < size; i++) {
JSONObject jObj = jArray.getJSONObject(i);
System.out.println(" Price : " + jObj.get("price").toString());
System.out.println(" Address : " + jObj.get("address").toString());
}
}
} catch (MalformedURLException ex) {
// Manage Exception here
} catch (IOException ex) {
// Manage Exception here
}
I want to parse a JSON string:
MyJsonString:
{
"status": "ok",
"count": 2,
"count_total": 9,
"pages": 5,
"posts": [
{
"id": 432,
"type": "post",
"title": "Title 1"
},
{
"id": 434,
"type": "post",
"title": "Title 2"
}
]
}
I have gone through:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
The examples work fine,but for that,i edited the JSON string to make it a Java String.
Ex:
JSON String:
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
I edited to:
String jsonStr = "{menu: {" +
"id: file," +
"value: File," +
"popup: {" +
"menuitem: [" +
"{value: New, onclick: CreateNewDoc()}," +
"{value: Open, onclick: OpenDoc()}," +
"{value: Close, onclick: CloseDoc()}" +
"]" +
"}" +
"}}";
But when i try to parse this myJsonString after accordingly editing it to be a valid Java String and run the project,it gives me warning and it does not display the Toast message which gives me titles.
Logcat:
10-19 18:36:45.972: WARN/System.err(1250): org.json.JSONException: Unterminated object at character 101 of { status : ok ,count : 2,count_total : 9,pages : 5,posts : [{id : 432,type : post ,title : Title 1 ,},{id : 434,type : post ,title : Title 2 ,},]}
I don't know where I am doing wrong? Even I have no idea,how to make Json String to a valid Java String programatically?
Any help appreciated.
Edit:
String jsonString="{\" status : ok \",\"count : 2\",\"count_total : 9\",\"pages : 5\",\"posts\" : [{\" id\" : \"432\",\"type\": \" post\", \"title\" : \" Title 1 \"},{ \"id \": \"434\",\type : post ,\"title\" : \" Title 2\"}]}";
JSONObject jsonObj = new JSONObject(jsonString);
String status_value = jsonObj.getString("status");
Toast.makeText(context,"Status_value= "+status_value, Toast.LENGTH_LONG).show();
I tried to toast status value this way.But I can't. Please help.
In your case the response of the JSON coming is not a valid one.
"count": 2, which is not the correct way it should be in double quotes like this
"count": "2", same way for the rest of the response String also.
UPDATED:
You exact JSONString that you have created is wrong, just replace my string and checkout.
First String
String jsonString = "{\"status\": \"ok\",\"count\": \"2\",\"count_total\": \"9\",\"pages\": \"5\",\"posts\":" +
"[{\"id\": \"432\",\"type\": \"post\",\"title\": \"Title 1\"}," +
"{\"id\": \"434\",\"type\": \"post\",\"title\": \"Title 2\"}]}";
Second String
String jsonStr = "{\"menu\": {\"id\": \"file\",\"value\": \"File\",\"popup\": {\"menuitem\": " +
"[{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},{\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}," +
"{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
The string in your java code is NOT a valid JSON string. you do not enclode the strings with quotes. try this one:
String example = "[\"a\", \"b\", \"c\"]";
This should give you a string array.