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);
}
}
Related
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");
I'm trying to do a post request in Android Studio written in Kotlin
I'm posting a JSON object to our server and then the server is returning a JSON object back. But what I'm doing here is decoding the response body as a string and then converting it into the data structure we need. I'm sure there is a better and simpler way to do what I need done.
My current code works but the major issue I'm having is formatting the string if our objects have nested objects which is why I want to figure out a better way to turn the response body into a json object.
I'm not too familiar with many request libraries for kotlin but I have looked into okhttp3 but I'm not sure how to post a json object, attach headers and decode the response body into a json object.
I know for okhttp3 I need to convert the json object to a string to post other than that I'm lost.
Breakdown of what's needed:
Post JSON Object To Server
Send Headers With Post Request
Decode Response Body into JSON Object/ Kotlin Equivalent
Simplify What I'm Trying to Do if Possible
This is the current code I have
private fun postRequestToGetDashboardData() {
val r = JSONObject()
r.put("uid", muid)
r.put("token", mtoken)
SendJsonDataToServer().execute(r.toString());
}
inner class SendJsonDataToServer :
AsyncTask<String?, String?, String?>() {
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
if (result.equals(null)) {
val t = Toast.makeText(this#Home, "No devices to display", Toast.LENGTH_LONG)
t.setGravity(Gravity.CENTER, 0, 0)
t.show()
} else {
intentForUnique.putExtra("FirstEndpointData", result)
var list = handleJson(result)
adapter.submitList(list)
dashboardItem_list.adapter = adapter
adapter.notifyDataSetChanged();
dashboardItem_list.smoothScrollToPosition(0);
}
}
override fun doInBackground(vararg params: String?): String? {
val JsonDATA = params[0]!!
var urlConnection: HttpURLConnection? = null
var reader: BufferedReader? = null
try {
val url = URL("URL");
urlConnection = url.openConnection() as HttpURLConnection;
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", mtoken);
urlConnection.setRequestProperty("Accept", "application/json");
val writer: Writer =
BufferedWriter(OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
writer.close();
val inputStream: InputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = BufferedReader(InputStreamReader(inputStream))
var inputLine: String? = reader.readLine()
if (inputLine.equals("null")) {
return null
} else {
return inputLine
}
} catch (ex: Exception) {
Log.e(TAG, "Connection Failed", ex);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (ex: Exception) {
Log.e(TAG, "Error closing stream", ex);
}
}
}
return null
}
}
private fun handleJson(jsonString: String?): ArrayList<SensorData> {
val jsonArray = JSONArray(jsonString)
val list = ArrayList<SensorData>()
var x = 0
while (x < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(x)
list.add(
SensorData(
jsonObject.getInt("deviceId"),
// jsonObject.getString("deviceName"),
jsonObject.getInt("battery"),
jsonObject.getString("dateTime"),
jsonObject.getInt("airValue"),
jsonObject.getInt("waterValue"),
jsonObject.getInt("soilMoistureValue"),
jsonObject.getInt("soilMoisturePercent")
)
)
x++
}
return list
}
So the json data being returned back is an array of this structure (our backend is written in Go)
type Device struct {
DeviceID int `bson:"deviceId" json:"deviceId"`
Battery int `bson:"battery" json:"battery"`
DateTime time.Time `bson:"dateTime" json:"dateTime"`
AirValue int `bson:"airValue" json:"airValue"`
WaterValue int `bson:"waterValue" json:"waterValue"`
SoilMoistureValue int `bson:"soilMoistureValue" json:"soilMoistureValue"`
SoilMoisturePercent int `bson:"soilMoisturePercent" json:"soilMoisturePercent"`
}
I am generating a JSON output in php which i need to use to fill line chart in android application writen in kotlin.
The JSON data is:
[{"reading_temperature":"14","hour":"01"},{"reading_temperature":"14","hour":"02"},{"reading_temperature":"14","hour":"03"},{"reading_temperature":"14","hour":"04"},{"reading_temperature":"14","hour":"05"},{"reading_temperature":"14","hour":"06"},{"reading_temperature":"14","hour":"07"},{"reading_temperature":"14","hour":"08"},{"reading_temperature":"14","hour":"09"},{"reading_temperature":"14","hour":"10"},{"reading_temperature":"14","hour":"11"},{"reading_temperature":"14","hour":"12"},{"reading_temperature":"14","hour":"13"},{"reading_temperature":"14","hour":"14"},{"reading_temperature":"14","hour":"15"},{"reading_temperature":"14","hour":"16"},{"reading_temperature":"14","hour":"17"},{"reading_temperature":"14","hour":"18"},{"reading_temperature":"14","hour":"19"},{"reading_temperature":"14","hour":"20"},{"reading_temperature":"14","hour":"21"},{"reading_temperature":"14","hour":"22"},{"reading_temperature":"14","hour":"23"}]
This is the part of the code where i get the JSON:
override fun doInBackground(vararg params: String?): String? {
var response:String?
try{
response = URL("https://127.0.0.1/weatherStation/temperatureDaily.php").readText(
Charsets.UTF_8
)
}catch (e: Exception){
response = null
}
return response
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
try {
val jsonObj = JSONObject(result)
} catch (e: Exception) {
}
}
Now i need to use that data to populate the line chart, this is hardcoded data which i need to exchange with JSON
private fun setupLineChartDataTemperatura() {
val yVals = ArrayList<Entry>()
//This next part i need to dynamically generate from JSON,
//first float value and last string value should be `"hour":"xx"`
// and second float value should be `[{"reading_temperature":"xx"`
yVals.add(Entry(0f, 4f, "0"))
yVals.add(Entry(1f, 5f, "1"))
yVals.add(Entry(1.5f, 4f, "1.5"))
yVals.add(Entry(2f, 5f, "2"))
yVals.add(Entry(3f, 3f, "3"))
yVals.add(Entry(4f, 2f, "4"))
val set1: LineDataSet
set1 = LineDataSet(yVals, "Temperatura")
val dataSets = ArrayList<ILineDataSet>()
dataSets.add(set1)
val data = LineData(dataSets)
chart1.setData(data)
chart1.description.isEnabled = false
chart1.legend.isEnabled = true
chart1.setPinchZoom(false)
chart1.xAxis.enableGridDashedLine(5f, 5f, 0f)
chart1.axisRight.enableGridDashedLine(5f, 5f, 0f)
chart1.axisLeft.enableGridDashedLine(5f, 5f, 0f)
chart1.setDrawGridBackground(true)
chart1.xAxis.labelCount = 11
chart1.xAxis.position = XAxis.XAxisPosition.BOTTOM
chart1.setTouchEnabled(true)
chart1.invalidate()
}
I have managed to do it:
val jsonTemperatureData = JSONArray(result)
for (i in 0 until jsonTemperatureData.length()) {
val item = jsonTemperatureData.getJSONObject(i)
val reading_temperature = item.getString("reading_temperature")
val hour = item.getString("hour")
yVals.add(Entry(hour.toFloat(), reading_temperature.toFloat(), hour.toString()))
}
{
"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"));
}
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.