JSONObject error when executing code to update remote JSON file - java

I am trying to update a JSON file with input from an HTTP GET request. I so far have the following below but it is returning an org.json.simple.JSONObject cannot be cast to org.json.JSONObject. I have tried numerous methods with this but I am hitting the same hurdle and going round in circles. Please help me.
The goal after seeing the revised JSON data outputted to system is to write it back to file.
HTTP GET RESPONSE FORMAT:
{
array: [
"data1" : "data 1",
"data2" : "data 2",
"data3" : "data 3",
"data4" : "data 4",
"data5" : "data 5",
]
}
EXISTING JSON FILE (please note no array):
{
"data5" : "data 5",
"dataA" : "data A",
"dataB" : "data B",
"dataC" : "data C",
"dataD" : "data D",
}
HTTP GET CODE:
#Component
public class ServiceConnector {
private final HttpClient client;
public ServiceConnector() {
client = HttpClientBuilder.create().build();
}
public String get(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
HttpGet request = new HttpGet(url);
request.addHeader("Accept", acceptHeader);
if (bearerToken.isPresent()) {
request.addHeader("Authorization", "Bearer " + bearerToken.get());
}
try {
HttpResponse response = client.execute(request);
//new code
String data = EntityUtils.toString(response.getEntity());
JSONObject root = new JSONObject(data);
JSONArray results = root.getJSONArray("results");
for(int i = 0; i < results.length(); i++) {
JSONObject jsonResult = results.getJSONObject(i);
OBLI Result = new OBLI();
String data1 = jsonResult.getString("data1");
String data2 = jsonResult.getString("data2");
String data3 = jsonResult.getString("data3");
String data4 = jsonResult.getString("data4");
String data5 = jsonResult.getString("data5");
try {
FileReader reader = new FileReader("/root/Desktop/data.json");
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(reader);
System.out.println(jsonObject);
JSONObject dataObj = (JSONObject) jsonObject.get("data5");
System.out.println(periodObj);
dataObj.put("data5",data5);
System.out.println(jsonObject);
}
catch (IOException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
e.printStackTrace();
}
}
//end of new code
if (response.getStatusLine().getStatusCode() == 401) {
throw new UnauthorizedException();
}
return "something else later";
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}

I think the problem with "HTTP GET RESPONSE FORMAT".
maybe right JsonArray format is:-
{
"array": [{
"data1" : "data 1",
"data2" : "data 2",
"data3" : "data 3",
"data4" : "data 4",
"data5" : "data 5"
}]
and then you can change
JSONArray results = root.getJSONArray("results"); to JSONArray results = root.getJSONArray("array");
and then use for-each loop for get one by one Object With help of DTOs.
}
So, you can convert jsonArray to JsonObject.

The answer to this question was that org.json and org.json.simple did not create JSONObjects that were interchangeable.
I used Jackson library and ObjectMapper, JsonNode, and ObjectNode to update the file - ultimately removing the org.json.simple library altogether.

Related

Parse JSON with 2 objects before an array

I'm currently trying to parse some JSON in my android application but I keep getting an error saying "No value for users"
This is the current code I am using:
JSONObject parentObject = new JSONObject(finalJSON);
JSONObject childObject = new JSONObject(String.valueOf(parentObject));
JSONArray parentArray = childObject.getJSONArray("users");
JSONObject finalObject = parentArray.getJSONObject(0);
String userName = finalObject.getString("username");
String profileLink = finalObject.getString("profileimage");
Log.d("JSON", String.valueOf(finalObject));
return profileimage+ " - " + profileLink ;
and here is my JSON:
{
"reply": {
"users": [
{
"userid": "001",
"loggedIn": 1,
"username": "joe.bloggs",
"profileimage": "http://127.0.0.1/joebloggs.png",
"realname": "Joe Bloggs",
}
]
}
}
Thanks in advance!
You forgot the reply level.
Here is what you should do.
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray userArray = parentObject
.getJSONObject("reply")
.getJSONArray("users");
JSONObject finalObject = userArray.getJSONObject(0);
you can't take new object for object inside object.
you have to do this for parse object inside object.
JSONObject object1 = new JSONObject(finalJSON);
JSONObject object2 = object1.getJSONObject("reply");
JSONArray jsonArray = object2.getJSONArray("users");
JSONObject object3 = jsonArray.getJSONObject(0);
try the following:
JSONObject root = null;
try {
root = new JSONObject("reply");
JSONArray childArray = root.getJSONArray("users");
String userName = childArray.getString(0);
.
.
.
} catch (JSONException e) {
e.printStackTrace();
}

Generate 2d Json Array In Java

I'm trying to generate a 2d JSON array using JSON object in Java. I'm trying to generate the following JSON.
Java Code..
JSONObject root = new JSONObject();
JSONObject c0 = new JSONObject();
JSONObject c1 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONObject buttons = new JSONObject();
root.put("recipient", c0);
root.put("message", c1);
c0.put("id", userId);
c1.put("message", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "button");
payload.put("text", "What do you want to do next");
payload.put("buttons", buttons);
buttons.put("type", "web_url");
buttons.put("url", "https://google.com");
buttons.put("title", "show website");
buttons.put("type", "postback");
buttons.put("title", "Hi There");
buttons.put("payload", "sample payload");
Expected JSON Output..
{
"recipient":{
"id":"USER_ID"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"web_url",
"url":"https://google.com",
"title":"Show Website"
},
{
"type":"postback",
"title":"Start Chatting",
"payload":"Sample_PAYLOAD"
}
]
}
}
}
}
Current Output..
{
"recipient":{"
id":"988459377921053"
},
"message":{
"message":{"
payload":{
"buttons":{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
},
"template_type":"button",
"text":"What do you want to do next"},
"type":"template"
}
}
}
I'm creating nested Json objects and adding them from the outer level to the inner level still the output JSON is not as expected. Can't understand where I'm going wrong.
Edit 1:
Tried changes mentioned by user #user1802604 but the JSON being generated is of the following format..
{
"recipient":{
"id":"988459377921053"
},
"message":{
"attachment":{
"payload":{
"buttons":[
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
},
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
}
],
"template_type":"button",
"text":"What do you want to do next"
},
"type":"template"
}
}
}
The API to which I'm sending the JSON is returning response code 400 with message "Bad Request". Is there a way to preserve the order of elements??
I think most of your codes are right. Only two errors need to be fixed.
Note that I'm not sure what library you're using for representing json, so the following codes may not fully correct. I assume that you're using org.json.
c1.put("message", attachment); should be c1.put("attachment", attachment);.
JSONObject buttons = new JSONObject(); should be created as JSONArray buttons = new JSONArray();. So you also have to create another json object for storing type, title, and url.
JSONArray buttons = new JSONArray();
JSONObject button1 = new JSONObject();
button1.put("type", "web_url");
button1.put("url", "https://google.com");
button1.put("title", "show website");
buttons.put(button1);
JSONObject button2 = new JSONObject();
button2.put("payload", "postback");
button2.put("url", "Sample_PAYLOAD");
button2.put("title", "Start Chatting");
buttons.put(button2);
This code is settings value of a JSONObject
buttons.put("type", "web_url");
buttons.put("url", "https://google.com");
buttons.put("title", "show website");
buttons.put("type", "postback");
buttons.put("title", "Hi There");
buttons.put("payload", "sample payload");
Since there is twice each key, you override the first value.
What you want is to add a JSONObject instance into a JSONArray buttons.
JSONArray arrayButton= new JSONArray();
JSONObject button.put("type", "web_url");
button.put("url", "https://google.com");
button.put("title", "show website");
arrayButton.put(button);
button.put("type", "postback");
button.put("title", "Hi There");
button.put("payload", "sample payload");
arrayButton.put(button);
To add each object into an array. Then simply add the array you have build.

Extract json subset with few attributes from the main json

Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.
https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.

Android data transferring with Json issue

This is my json array creating with php.
I want to know bellow json array have correct syntax.
How to get the values withing android,because my sample code get some errors.
THIS IS PHP SCRIPT FOR JSON ARRAY GENARATING
public static function getCategory($_lgtime) {
$con = JsonDataManip::connect();
$stmt = $con->prepare("select * from " . _TABLE_CATEGORY . " where lgtime > ?");
$stmt->execute(array($_lgtime));
while ($row = $stmt->fetch()) {
$jsonArray['key'] = $row['key'];
$jsonArray['name'] = $row['name'];
$jsonArray['lgtime'] = $row['lgtime'];
$json[] = $jsonArray;
}
return $json;
}
usage php :
echo json_encode(JsonDataManip::getCategory('20140129184514895'));
GENARATED JSON ARRAY
[{
"key":"1",
"name":"Category 10",
"lgtime":"20140129184514896"
},
{
"key":"2",
"name":"Category 9",
"lgtime":"20140129184514896"
},
{
"key":"3",
"name":"Category 8",
"lgtime":"20140129184514896"
}]
ANDROID JSON PARSER FUNCTION
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsnArry = new JSONObject(jsonStr);
JSONArray jsonArray = jsnArry.getJSONArray("");
for(int i=0;i<jsnArry.length();i++){
Log.d("JSON PARSE",jsonArray.getJSONObject(i).getString("name"));
//contactList[i] =
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
ERROR
01-30 08:45:53.527: W/System.err(1507): org.json.JSONException: Value {"lgtime":"20140129184514896","key":"1","name":"Category 10"} at 0 of type org.json.JSONObject cannot be converted to JSONArray
Your PHP script returns a JSON array, not a JSON object. You should update your Android code like so:
if (jsonStr != null) {
try {
JSONArray json = new JSONArray(jsonStr);
for (int i=0; i < json.length(); i++) {
Log.d("JSON PARSE", json.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
Log.w("JSON PARSE", "Failed to parse JSON!", e);
}
}
To check if your JSON string is valid, please use this link JSONLint.
As far your error is concerned for your code, it clearly states that
type org.json.JSONObject cannot be converted to JSONArray
Possible Solution (if you are using Gson)
Your response from ServiceHandler would be a string. So convert that into a JSONObject and the pass that to JSONArray.
Example
JSONObject jsonObject = new JSONObject(<responseString>);
JSONArray jsonArray = jsonObject.getJSONArray();
Else
JSONObject jsonObject = new JSONObject(<responseString>);
String key = jsonObject.getJSONObject("key");
String name = jsonObject.getJSONObject("name");
String lgtime = jsonObject.getJSONObject("lgtime");
Then you can continue with your logic in the program.
{ "employees":[
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
]
}
Your opening and closing braces are missing. that is not a valid json array, The above is a sample array format

How to Parse the JSON String Android

I'm trying to Parse the below JSONString
[[{"0":"
","title":" Technical Support Analyst in Noida","1":"
","Company Name":" Oracle","2":"
","Category":"Fresher","3":"
","Job Type":"Full Time","4":"
","Location":"Noida","5":"
","Job Qualification":"BE\/BTch\/Bsc\/Others","6":"
","Job Experience":"Freshers","7":"
","Job postdate":"2013-6-05","8":"
"}]]
Here My Code:
// try parse the string to a JSON object
try {
//jObj = new JSONObject(JsonString);
JSONArray ja = new JSONArray(result);
int size = ja.length();
Log.d("tag", "No of Elements " + ja.length());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Could any one help,My Code is not Working?
I want to Parse title,CompanyName,Category Etc...
You need to create JSONArray from your jsonstring.
You have JSONArray inside JSONArray and then JSONObect..
try {
JSONArray ja = new JSONArray(buffer.toString());
JSONArray innerJsonArray = ja.getJsonArray(0);
JSONObject object = innerJsonArray.getJSONObject(0);
String title = object.getString("title");
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Take a look at this Json parsing guide using native tools and Gson library that I wrote:
Json Parsing
Maybe you will find it useful.
You can download the full project from there as well to run and test it for yourself.
You need to structure your json.
There is no array named "result". What you have to do is to name every element of the json with a unique name, so as to fetch it.
such as
{"result":
["result1":["result2":{"0":"
","title":" Technical Support Analyst in Noida","1":"
","Company Name":" Oracle","2":"
","Category":"Fresher","3":"
","Job Type":"Full Time","4":"
","Location":"Noida","5":"
","Job Qualification":"BE\/BTch\/Bsc\/Others","6":"
","Job Experience":"Freshers","7":"
","Job postdate":"2013-6-05","8":"
"}]]}
You can try below code for parsing JSON
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea, Republic of"},
{"countryCode":"us","countryName":"United States"},
{"countryCode":"jp","countryName":"Japan"},
{"countryCode":"cn","countryName":"China"},
{"countryCode":"in","countryName":"India"}
]
}
parsing code
public static ArrayList<Country> ParseJson(String jsonstring) {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String status;
String message = "";
try {
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}
} catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
return arrCountries;
}

Categories