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.
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 am trying to parse the following JSON. But getting exception please help.
{
"method": "demo",
"clazz": "storage",
"params": [
"",
"LOGIN",
"{"auth": {"tenantName": "AUTH_Tonny", "casauth": {"username": "Tonny", "tgt": "TGT-1876hkahaadcaweyfiowufssadsfsdf"}}}",
"http://ipstorage.google.com"
]
}
Here is the Java Code:
String tokenId = "";
String message = "LOGIN";
String url1 = "http://ipstorage.google.com";
String authentication = "{\"auth\": {\"tenantName\": \"AUTH_" + test2.getUsername()
+ "\", \"casauth\": {\"username\": \""
+ test2.getUsername() + "\", \"tgt\": \""
+ test2.getPassword() + "\"}}}";
String pp = "[\"" + tokenId + "\",\"" + message + "\",\""
+ authentication + "\",\"" + url1 + "\"]";
String msg1 = "{\"method\":\"demo\",\"clazz\":\"storage\",\"params\":" + pp + "}";
System.out.println(msg1);
JSONObject jo = (JSONObject) new JSONParser().parse(msg1);
System.out.println("##");
System.out.println(jo);
Output and exception which I am getting is:
{"method":"demo","clazz":"storage","params":["","LOGIN","{"auth":
{"tenantName": "AUTH_Tonny", "casauth": {"username": "Tonny", "tgt": "TGT -
1876 hkahaadcaweyfiowufssadsfsdf"}}}","http://ipstorage.google.com"]}
Exception in thread "main" Unexpected character (a) at position 59.
at org.json.simple.parser.Yylex.yylex(Unknown Source)
at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at com.t.g.i.e.utils.Test.main(Test.java:74)
Please help me out. Thank you in advance.
You can use http://www.jsoneditoronline.org/ to validate your json file.
{
"method": "demo",
"clazz": "storage",
"params": [
"",
"LOGIN",
{
"auth": {
"tenantName": "AUTH_Tonny",
"casauth": {
"username": "Tonny",
"tgt": "TGT-1876hkahaadcaweyfiowufssadsfsdf"
}
}
},
"http://ipstorage.google.com"
]
}
Your JSON format not right. Maybe You want JSON like this,
{
"method": "demo",
"clazz": "storage",
"params": [
"",
"LOGIN",
{"auth": {"tenantName": "AUTH_Tonny", "casauth": {"username": "Tonny", "tgt": "TGT-1876hkahaadcaweyfiowufssadsfsdf"}}},
"http://ipstorage.google.com"
]
}
There no " before and after JSONObject. You can check your JSON Format with this tools.
https://jsonformatter.curiousconcept.com/
Your java code should like this,
...
String pp = "[\"" + tokenId + "\",\"" + message + "\","
+ authentication + ",\"" + url1 + "\"]";
...
to remove " in your JSON.
Use a Json validator to validate the string
and use a json parser libraries such as Gson or Jackson, it would automate a lot of your work and you don't need to code much to parse
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
I want to add additional property to json string without transform the String to any object format (I am doing the transformation right now which taking 30 ms time, i want to avoid the transformation time), so is there any way to add property to the json string without transform the payload to any object format?
Ex:
{
"type": "some type",
"data": [{
"email": "email id",
"content": {
"some filed": "filed value"
}
}]
}
i need my payload after the new field added like.,
{
"type": "some type",
"data": [{
"email": "email id",
"content": {
"some filed": "filed value",
"new field": "New value"
}
}]
}
You can use regex to slip in your new field at the end of content:
String json = "{ \"type\": \"some type\", \"data\": [{ \"email\": \"email id\", \"content\": { \"some filed\": \"filed value\" } }] }";
String newField = "\"new field\": \"New value\"";
json = json.replaceAll("(\"content\".*?)\\}", "$1" + Matcher.quoteReplacement("," + newField + "}") + "");
I am trying to extract specific data from a json response using org.json.JSONObject library
Heres is my json response :
{
"facets": {
"application": [
{
"name": "38",
"distribution": 1
}
],
"node": [
{
"name": "frstlwardu03_05",
"distribution": 1
}
],
"area": [
{
"name": "x",
"distribution": 1
}
],
"company": [
{
"name": "war001",
"distribution": 1
}
]
},
"duObjects": [
{
"id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000",
"name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)",
"mu": "ZSRPSRM000",
"label": "",
"session": "ZRM760J|000",
"sessionLabel": "SAP SRM Achats frais generaux execution",
"uprocHeader": "ZRM760JU00|000",
"uprocHeaderLabel": "Header for SRM760J",
"uprocHeaderType": "CL_INT",
"domain": "M",
"domainLabel": "",
"application": "38",
"applicationLabel": "magasin",
"highlightResult": {
"name": "name",
"word": "TSK"
}
}
],
"totalCount": 1,
"pageSize": 10,
"pageCurrent": 1,
"pageNb": 1
}
Here is the method I used to convert the URL call to a jsonobject :
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
When I call this method I am able to get the data in teh Duobject :
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?
searchString=TSK(ZRM760J)(000)(ZRM760JU00)
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10");
System.out.println(json.getJSONArray("duObjects"));
}
Is there anyway I can extract only the name field of the DuObjects?
You can use
System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name"));
to get the name.
1 : your complete response is a JSON OBJECT
2 : if any element is written like
"some key name " : { " some value " }
this is a JSON Object
3 : if any element is writen like
"some key name " : " some value "
this is value inside you json object which you can get by
jsonObject.getString("key name")
4 : if any element is writen like
"some key name " : [ " some value " ]
then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")
and then you can traverse the elements of the JSON ARRAY by
`jsonArrayObj.get(0);`
You can use Jackson libraries to covert to java. Jackson api provides annotation level and it automatically converts json to pojo object and object to json vice versa . refer this link. you can get good idea about this
http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/