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
Related
I am writing api tests. I am using rest assured to make the requests the following way:
public void POSTNewRequest(String endpoint, String requestBody){
response = given().auth().none()
.header("Content-Type", "application/json")
.contentType(ContentType.JSON)
.when()
.body(requestBody).log().all()
.post(endpoint);
}
The requestBody I'm passing in the request is constructed by converting custom java objects to a string using ObjectMapper.writeValueAsString(requestBody).
This method has been working great for me, but now I need to make a bunch of requests where there is a certain field missing. eg:
{
"foo": [
{
"description": "dflt desc",
"ref": "abcd",
"FIELDTOREMOVE": 0,
"customArray": {
"number": 22,
"letter": "B"
}
}
],
"moreInfo": {
"email": "test#test.be",
"name": "Jhon Doe"
}
}
Now I would like to remove the field "FIELDTOREMOVE" inside this request just before the post method. I tried to convert the requestBody string to a JsonNode and then removing the field but it doesn't remove the field.
private void removeNullFields(String requestBody) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(requestBody);
System.out.println(jsonNode.get("FIELDTOREMOVE"));
((ObjectNode)jsonNode).remove("FIELDTOREMOVE");
}
And when I try to print the value the field its returning "null" so I'm obviously doing something wrong...
I also tried achieving the same by using the gson library with similar results so I guess there is a misunderstanding on my end but can't figure out where to look to fix my problem.
In short: I'm making api requests using the rest assured library by passing a string as the body but in this string I sometimes have to remove certain fields the check what response I'm getting.
The "foo" in your JSON is an array. You should do:
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(requestBody);
jsonNode.get("foo").forEach(e -> ((ObjectNode) e).remove("FIELDTOREMOVE"));
System.out.println(jsonNode.toPrettyString());
Output:
{
"foo" : [ {
"description" : "dflt desc",
"ref" : "abcd",
"customArray" : {
"number" : 22,
"letter" : "B"
}
} ],
"moreInfo" : {
"email" : "test#test.be",
"name" : "Jhon Doe"
}
}
You can use this library:
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
So that the code would look like:
import org.json.JSONObject;
public class JSONManipulation {
static final String JSON = "{\n" +
" \"foo\": [\n" +
" {\n" +
" \"description\": \"dflt desc\",\n" +
" \"ref\": \"abcd\", \n" +
" \"FIELDTOREMOVE\": 0,\n" +
" \"customArray\": {\n" +
" \"number\": 22,\n" +
" \"letter\": \"B\"\n" +
" }\n" +
" }\n" +
" ],\n" +
" \"moreInfo\": {\n" +
" \"email\": \"test#test.be\",\n" +
" \"name\": \"Jhon Doe\"\n" +
" }\n" +
"}";
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject(JSON);
System.out.println("Value before edit: " + jsonObject.toString());
jsonObject.getJSONArray("foo").getJSONObject(0).remove("FIELDTOREMOVE");
System.out.println("Value after edit: " + jsonObject.toString());
}
}
The output would be:
Value before edit: {"foo":[{"FIELDTOREMOVE":0,"ref":"abcd","description":"dflt desc","customArray":{"number":22,"letter":"B"}}],"moreInfo":{"name":"Jhon Doe","email":"test#test.be"}}
Value after edit: {"foo":[{"ref":"abcd","description":"dflt desc","customArray":{"number":22,"letter":"B"}}],"moreInfo":{"name":"Jhon Doe","email":"test#test.be"}}
So you can manipulate with your JSON content and then post is as a String.
I'm trying to parse below JSON and looking for "zip-code" value "526262". I'm new to Java and struggling to get the zip-code value?
This is my JSON:
{
"id": "6fffdfdf-8d04-4f4e-b746-20930671bd9c",
"timestamp": "2017-07-21T03:51:27.329Z",
"lang": "en",
"result": {
"source": "testsrc",
"resolvedQuery": "testquery",
"action": "test",
"actionIncomplete": true,
"parameters": {
"zip-code": "526262"
}
}
}
And this is my Java code:
String test= "{\n" +
"\t\"id\": \"6fffdfdf-8d04-4f4e-b746-20930671bd9c\",\n" +
"\t\"timestamp\": \"2017-07-21T03:51:27.329Z\",\n" +
"\t\"lang\": \"en\",\n" +
"\t\"result\": {\n" +
"\t\t\"source\": \"testsrc\",\n" +
"\t\t\"resolvedQuery\": \"testquery\",\n" +
"\t\t\"action\": \"test\",\n" +
"\t\t\"actionIncomplete\": true,\n" +
"\t\t\"parameters\": {\n" +
"\t\t\t\"zip-code\": \"526262\"\n" +
"\t\t}\n" +
"\t}\n" +
"}";
JSONObject request = new JSONObject(test);
String zipCode = request.getJSONObject("result").get("parameters").toString();
System.out.println("zipCode is : " + zipCode);
But I'm getting below output:
zipCode is : {"zip-code":"526262"}
How to get zip-code value alone?
Can someone help how to get this value in java?
You should use getJSONObject when getting parameters so that you can keep using the JSONObject API to dig deeper.
request.getJSONObject("result").getJSONObject("parameters").getString("zip-code");
request.getJSONObject("result").get("parameters").getString("zip_code")
will solve your problem. JSON objects are built to handle nesting.
I have a JSON file and need to get the parameter ' fulltext ' , but I'm new to JSON and do not know how to retrieve it in Java . Could someone explain to me how caught this value fulltext ?
Here a piece of the file in JSON.
{
"head": {
"vars": [ "author" , "title" , "paper" , "fulltext" ]
} ,
"results": {
"bindings": [
{
"author": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/person/richard-scheines" } ,
"title": { "type": "literal" , "value": "Discovering Prerequisite Relationships among Knowledge Components" } ,
"paper": { "type": "uri" , "value": "http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492" } ,
"fulltext": { "type": "literal" , "value": "GET TEXT" }
} ,
Json library download from here jar dowonload form here
Add this code in JSonParsing.java
import org.json.*;
public class JSonParsing {
public static void main(String[] args){
String source = "{\n" +
" \"head\": {\n" +
" \"vars\": [ \"author\" , \"title\" , \"paper\" , \"fulltext\" ]\n" +
" } ,\n" +
" \"results\": {\n" +
" \"bindings\": [\n" +
" {\n" +
" \"author\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/person/richard-scheines\" } ,\n" +
" \"title\": { \"type\": \"literal\" , \"value\": \"Discovering Prerequisite Relationships among Knowledge Components\" } ,\n" +
" \"paper\": { \"type\": \"uri\" , \"value\": \"http://data.linkededucation.org/resource/lak/conference/edm2014/paper/492\" } ,\n" +
" \"fulltext\": { \"type\": \"literal\" , \"value\": \"GET TEXT\" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}\n" +
"";
JSONObject main = new JSONObject(source);
JSONObject results = main.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
JSONObject firstObject = bindings.getJSONObject(0);
JSONObject fulltextOfFirstObject = firstObject.getJSONObject("fulltext");
String type = fulltextOfFirstObject.getString("type");
String value = fulltextOfFirstObject.getString("value");
System.out.println("Type :"+ type+"\nValue :"+value);
}
}
NOTE: In JSON {} represents jsonObject and [] represents jsonArray.
You can use org.json/Jackson to convert this string to JSONObject.
If it is a JSONObject called val;
then val.get("results").get("bindings").get(0).get("fulltext")
will give you the full text of first element of bindings.
There are many good JSON parsing libraries for Java. Try out Org.JSON (Maven) or Jackson Library (Maven) or my personal favorite Google's GSON Library (Maven) that can convert Java Objects into JSON and back.
I recommend you using https://github.com/alibaba/fastjson , It's easy to use.
From a Rest API, I get json data in the following format:
[
{
"id": "1",
"item": "tea",
"price": "7.5",
"image": "http:\/\/192.168.1.3\/CI\/images\/tea.jpg",
"veg": "0",
"category": "drinks"
},
{
"id": "2",
"item": "coffee",
"price": "10",
"image": "http:\/\/192.168.1.3\/CI\/images\/coffee.jpg",
"veg": "0",
"category": "drinks"
}
]
From the API I get Json as a string and it contains backslashes in front of url's forward slashes, which is according to the json encoding specification. And I am correctly able to json_decode and get url from php. In android I store the json string in a variable named "menu_json".
Then I am trying to parse and get the image url from it using the following code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
try{
JSONObject menuApiObj = new JSONObject(menu_json);
JSONArray menuObj = menuApiObj.getJSONArray("menu");
for (int i = 0; i < menuObj.length(); i++){
JSONObject row = menuObj.getJSONObject(i);
rowString = row.getString("image");
imageUrl = row.toString();
Log.e("rowString", rowString);
Log.e("imageUrl", imageUrl);
}
The output I get is:
{
"id": "1",
"item": "tea",
"price": "7.5",
"image": "tea.jpg",
"veg": "0",
"category": "drinks"
}
The image field is supposed to be:
http://192.168.1.3/CI/images/tea.jpg
But instead I get just:
tea.jpg
When json_decode the API response in PHP, I get the correctly decoded url. But in Android, I am not getting the correctly decoded url in image field.
Please help!
Here is the complete API response:
{"menu":[{"id":"1","item":"tea","price":"7.5","image":"tea.jpg","veg":"0","category":"drinks"},{"id":"2","item":"cofee","price":"10","image":"coffee.jpg","veg":"0","category":"drinks"},{"id":"3","item":"crispy chicken","price":"160","image":"crispy-chicken.jpg","veg":"0","category":"curries"}],"cat_wise":[{"category":"drinks","items":[{"id":"1","item":"tea","price":"7.5","image":"http:\/\/192.168.1.3\/CI\/images\/tea.jpg","veg":"0","category":"drinks"},{"id":"2","item":"cofee","price":"10","image":"http:\/\/192.168.1.3\/CI\/images\/coffee.jpg","veg":"0","category":"drinks"}]},{"category":"curries","items":[{"id":"3","item":"crispy chicken","price":"160","image":"http:\/\/192.168.1.3\/CI\/images\/crispy-chicken.jpg","veg":"0","category":"curries"}]},{"category":"main","items":[]}]}
I'm not sure what Json library you're using, but it looks like org.json. I thought your code looked sane, so I implemented it and do not see the output that you are seeing. My guess is that your input data isn't what you expect it to be.
final JSONArray menuObj = new JSONArray("[\n" +
" {\n" +
" \"id\": \"1\",\n" +
" \"item\": \"tea\",\n" +
" \"price\": \"7.5\",\n" +
" \"image\": \"http://192.168.1.3/CI/images/tea.jpg\",\n" +
" \"veg\": \"0\",\n" +
" \"category\": \"drinks\"\n" +
" },\n" +
" {\n" +
" \"id\": \"2\",\n" +
" \"item\": \"coffee\",\n" +
" \"price\": \"10\",\n" +
" \"image\": \"http://192.168.1.3/CI/images/coffee.jpg\",\n" +
" \"veg\": \"0\",\n" +
" \"category\": \"drinks\"\n" +
" }\n" +
"]");
for (int i = 0; i < menuObj.length(); i++){
final JSONObject row = menuObj.getJSONObject(i);
System.out.println("imageUrl: " + row.getString("image"));
System.out.println("rowString: " + row);
}
Output:
imageUrl: http://192.168.1.3/CI/images/tea.jpg rowString:
{"image":"http://192.168.1.3/CI/images/tea.jpg","item":"tea","price":"7.5","veg":"0","id":"1","category":"drinks"}
imageUrl: http://192.168.1.3/CI/images/coffee.jpg rowString:
{"image":"http://192.168.1.3/CI/images/coffee.jpg","item":"coffee","price":"10","veg":"0","id":"2","category":"drinks"}
To parse JSON Array :
JSONArray jArray = jObject.getJSONArray("menu");
for (int i = 0; i < jArray.length(); i++) {
JSONObject innerjObject =jArray.getJSONObject(i);
String image =innerjObject.getString("image");
array_list.add(image);
}
output: http://192.168.1.3/CI/images/tea.jpg
And to display this image to imageview use library :
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
using Loadimagview method of library load image in imageview
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.