Modify the results of JSONObject - json

I am getting this response as JSON Object in jsp
{"Employeeslist":[{"name":"Decepticons0","id":"19990"}, {"name":"Decepticons1","id":"19991"},{"name":"Decepticons2","id":"19992"},{"name":"Decepticons3","id":"19993"},{"name":"Decepticons4","id":"19994"},{"name":"Decepticons5","id":"19995"},{"name":"Decepticons6","id":"19996"},{"name":"Decepticons7","id":"19997"},{"name":"Decepticons8","id":"19998"},{"name":"Decepticons9","id":"19999"},{"name":"Decepticons10","id":"199910"},{"name":"Decepticons11","id":"199911"},{"name":"Decepticons12","id":"199912"},{"name":"Decepticons13","id":"199913"},{"name":"Decepticons14","id":"199914"}]}
But what if I need only :
[{"name":"Decepticons0","id":"19990"},{"name":"Decepticons1","id":"19991"},{"name":"Decepticons2","id":"19992"},{"name":"Decepticons3","id":"19993"},{"name":"Decepticons4","id":"19994"},{"name":"Decepticons5","id":"19995"},{"name":"Decepticons6","id":"19996"},{"name":"Decepticons7","id":"19997"},{"name":"Decepticons8","id":"19998"},{"name":"Decepticons9","id":"19999"},{"name":"Decepticons10","id":"199910"},{"name":"Decepticons11","id":"199911"},{"name":"Decepticons12","id":"199912"},{"name":"Decepticons13","id":"199913"},{"name":"Decepticons14","id":"199914"}]
In jsp Am doing something like this :
JSONObject json = new JSONObject();
JSONArray employeeslist = new JSONArray();
JSONObject employee;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
employee = new JSONObject();
employee.put("name" , "Decepticons" + i);
employee.put("id" , "1999" + i);
employeeslist.add(employee);
}
json.put("Employeeslist", employeeslist);
}
catch (JSONException jse)
{
}
System.out.println(json.toString());

Replace the last line with:
System.out.println(employeeslist.toString());
This would output the array JSON string alone as required.

Related

A JSONArray text must start with '[' at 1 [character 2 line 1] : Need Help Parsing Json

I've been trying to parse this but am getting the error : Exception in thread "main" java.util.concurrent.CompletionException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
System.out.println("Which city would you like to find the weather for?");
try (Scanner s = new Scanner(System.in)) {
city = s.nextLine();
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=26aa1d90a24c98fad4beaac70ddbf274")).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse :: body)
//.thenAccept(System.out::println)
.thenApply(Main::parse)
.join();
}
public static String parse(String responseBody) {
JSONArray weather = new JSONArray(responseBody);
for (int i = 0; i < weather.length(); i++) {
JSONObject weatherObj = weather.getJSONObject(i);
int id = weatherObj.getInt("id");
// int userID = weatherObj.getInt("userId");
// String title = weatherObj.getString("title");
System.out.println(id + " "/* + title + " " + userID*/);
}
return null;
}
since your url returns an object, not array, try
JSONObject weather = new JSONObject(responseBody);
The API you are calling doesn't return an array but an object, so you have to deserialze to an object and not to an array. The data you are after is probably the weather property of that response object.
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray weather = jsonResponse.getJSONArray("weather");

JSON Object Exception

I am writing a web service-REST.
I am receiving a text_plain format.
Example of my data:
{"data_log":
{
"methodClass": [{"methodName": 1, "methodStatus": "1"},
{"methodName": 2, "methodStatus": "1"}]
}
}
In my Restful Webservice, I try to read the data, but I got error 500 Internal Server Error-JSON Object not found.
public int adaptiveAuth(String objDataLog){
logWriter("objDataLog:"+objDataLog);
JSONObject obj = new JSONObject(objDataLog);
JSONArray methodClassObj=(JSONArray)obj.get("methodClass");
if (methodClassObj != null) {
JSONObject methodObj;
String entrymethodName, entrymethodStatus;
for (Object o : methodClassObj) {
methodObj = (JSONObject) o;
entrymethodName = String.valueOf(methodObj.get("methodName"));
entrymethodStatus = String.valueOf(methodObj.get("methodStatus"));
logWriter("entrymethodName:"+entrymethodName);
logWriter("entrymethodStatus:"+entrymethodStatus);
}
}
}
I already tried to use the below code, but it still give me the error.
String methodClass= obj.getJSONObject("data_log").getString("methodClass");
I'm expecting to put the current data into an 2 dimension array which it would be like this:
[1,1],[2,1]
Anyone could give me some suggestion on how to solve this issue?
**Try this code for parsing json data**
ArrayList<HashMap<String, String>> list;
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray b= jsonObj.getJSONArray("methodClass");
// looping through All data
for (int i = 0; i < b.length(); i++) {
JSONObject c = b.getJSONObject(i);
String entrymethodName = c.getJSONObject("methodClass").getString("methodName");
String entrymethodStatus = c.getJSONObject("methodClass").getString("methodStatus");
// tmp hash map for storing values
HashMap<String, String> co = new HashMap<>();
// adding each child node to HashMap key => value
co.put(entrymethodName, entrymethodStatus );
// adding co to list
list.add(co);
Also check this - https://gist.github.com/codebutler/2339666
I changed by String to this format:
{ "methodSet": [
{
"methodName": 1,
"methodStatus": "1"
},
{
"methodName": 2,
"methodStatus": "1"
}
]
}
and for the code :
ArrayList<String> listMethod = new ArrayList<String>();
JSONArray arr=(JSONArray)obj.get("methodClass");
if (arr != null) {
JSONObject objMethod;
String MethodName, MethodStatus;
for (Object o : arr) {
objMethod = (JSONObject) o;
MethodName = String.valueOf(objMethod.get("methodName"));
MethodStatus = String.valueOf(objMethod.get("methodStatus"));
int resultMethodName = Integer.parseInt(MethodName);
int resultMethodStatus = Integer.parseInt(MethodStatus);
logWriter("MethodStatus"+resultMethodName);
logWriter("MethodName"+resultMethodStatus);
listMethod.add("(" + MethodName + "," + MethodStatus + ")");
logWriter("listMethod is : "+listMethod);
}
}

converting list in json response to comma delimed

Hi I have below json response object converted to string
json object:
{"docInformation":[{"docsWithinTheAlertingRegion":[2134,12521],"toatlNotifiedViaSms":0,"totalAccepted":1}]}
How to convert the docsWithinTheAlertingRegion":[2134,12521] to comma delimited text docsWithinTheAlertingRegion":2134,12521?
The output I want is json object:
{"docInformation":[{"docsWithinTheAlertingRegion":2134,12521,"toatlNotifiedViaSms":0,"totalAccepted":1}]}
Below is snippet of my code
**BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
System.out.println("line number:"+ inputLine);
response.append(inputLine);
}
in.close();
JSONObject jsonObj = new JSONObject(response.toString());
String str = XML.toString(jsonObj);**
i dont understand what your code do
But This Pure JS code do what u need
data={"docInformation":[{"docsWithinTheAlertingRegion":[2134,12521],"toatlNotifiedViaSms":0,"totalAccepted":1}]}
data.docInformation.forEach(function (info , index){
var tmresult =""
info.docsWithinTheAlertingRegion.forEach(function (x){
tmresult += "," + x.toString()
})
data.docInformation[index].docsWithinTheAlertingRegion =tmresult.substring(1)
})
print(data)

get particular value from json object

{
"CustomerDetails": [
{
"AccountName": "test",
"DnBNumber": 12342314
}
]
}
I want to get value from this json object.
I tried below but not working.
jsonObject.getJSONObject("AccountName").toString();
In the JSON you put, there are a JsonObject that contains a JsonArray, that contains two String, so..
final JSONObject jsonObject = new JSONObject(YOUR_JSON);
final JSONArray jsonArray = obj.getJSONArray("CustomerDetails");
for (int i = 0; i < geodata.length(); ++i) {
final JSONObject detail = geodata.getJSONObject(i);
System.out.println(detail.getString("AccountName"));
System.out.println(detail.getString("DnBNumber"));
}

How to get data from json one by one?

I have json datatype
{"email":"mikekhlau#gmail.com","contact":[{"contact_name":"Mike Lau","contact_no":"019-3331976"},{"contact_name":"Jason Lau","contact_no":"013-2711188"},{"contact_name":"Margaret Lau","contact_no":"019-3122281"}]}
How can I get email, contact_name and contact_no?
var json = {"email":"mikekhlau#gmail.com","contact":[{"contact_name":"Mike Lau","contact_no":"019-3331976"},{"contact_name":"Jason Lau","contact_no":"013-2711188"},{"contact_name":"Margaret Lau","contact_no":"019-3122281"}]}
You can get data by..
json.email
"mikekhlau#gmail.com"
json.contact[0].contact_name
"Mike Lau"
json.contact[0].contact_no
"019-3331976"
try {
JSONObject jsonRootObject = new JSONObject(strJson);
String email = jsonRootObject .getString("email");
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("contacts");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_name = jsonObject.getString("contact_name");
String contact_no= jsonObject.getString("contact_no");
}
} catch (JSONException e) {e.printStackTrace();}
}
use the above code