#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
try {
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output3;
}
//The string which is being passed from getVersion comprises of
[{"ipaddress":"10.253.140.116","password":"c0mcast!","username":"bwadmin"},{"ipaddress":"10.253.140.117","password":"bwadmin!","username":"bwadmin"}]
//My requirement is to access the value of ipaddress and password and username and store items in an array and send them to ConnectionStatus.
JSONArray jsonArr = new JSONArray(getVersionJson);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//Now you can fetch values from each JSON Object
}
JSONObject class represents just one JSON. This is generally inside braces { and }.
If the expected input getVersionJson is just one JSON object, your code works.
However, you are getting an array of JSON objects in the input string getVersionJson, so you need to use JSONArray class to handle an array of JSON Objects.
This is generally [ { }, { }, { }, ... ]
JSONArray extends List, so it can be iterated to read each JSONObject value.
Here is documentation for reference: Interface JsonArray.
Related
I'm making the bot for Google Dictionary using this API https://dictionaryapi.dev/. It's supposed to show word definitions in different languages. And the bot works just fine for English and Spanish. But there's an IOException every time I put in Russian words. What can be the cause of it?
Here's my Bot class.
Bot.java:
public void onUpdateReceived(Update update) {
//Model model = new Model();
WordModel wordModel = new WordModel();
Message message = update.getMessage();
if (message != null && message.hasText())
{
switch (message.getText()) {
case "/english":
DictionaryEntry.setLanguage("en");
sendMsg(message, DictionaryEntry.getLanguage());
break;
case "/russian":
DictionaryEntry.setLanguage("ru");
sendMsg(message, DictionaryEntry.getLanguage());
break;
case "/spanish":
DictionaryEntry.setLanguage("es");
sendMsg(message, DictionaryEntry.getLanguage());
break;
default:
if (!message.getText().contains("/")) {
try {
sendMsgs(message, DictionaryEntry.getWords(message.getText(), wordModel));
} catch (IOException e) {
sendMsg(message, "Не найдено");
sendMsg(message, DictionaryEntry.getUrl().toString());
}
}
break;
}
}
}
public void sendMsg(Message message, String text) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
public void sendMsgs(Message message, List<String> words) {
for (int i = 0; i < words.size(); i++) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(message.getChatId());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(words.get(i));
try {
//setButtons(sendMessage);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
And here's my DictionaryEntry class where I process JSON string that I get from URL.
DictionaryEntry.java:
private static String language = "ru";
public static String getLanguage() {
return language;
}
public static void setLanguage(String language) {
DictionaryEntry.language = language;
}
public static URL getUrl() {
return url;
}
private static URL url;
public static List<String> getWords(String message, WordModel wordModel) throws IOException {
url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
+ DictionaryEntry.getLanguage() + "/" + message);
Scanner in = new Scanner((InputStream) url.getContent());
String result = "";
while (in.hasNext())
{
result += in.nextLine();
}
String result2 = result.replaceAll("\"", "\\\"");
List<WordModel> models = new ArrayList<>();
List<String> results = new ArrayList<>();
int count = 0;
try {
JSONArray mainArray = new JSONArray(result2);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject wordEntry = mainArray.getJSONObject(i);
String wordName = wordEntry.getString("word");
wordModel.setWord(wordName);
JSONArray meaningsArray = wordEntry.getJSONArray("meanings");
for (int j = 0; j < meaningsArray.length(); j++) {
JSONObject meaningEntry = meaningsArray.getJSONObject(j);
JSONArray definitionsArray = meaningEntry.getJSONArray("definitions");
for (int k = 0; k < definitionsArray.length(); k++) {
//count++;
JSONObject definitionEntry = definitionsArray.getJSONObject(k);
String definition = definitionEntry.getString("definition");
wordModel.setDefinition(definition);
if (definitionEntry.has("example")) {
count++;
String example = definitionEntry.getString("example");
wordModel.setExample(example);
}
else {
wordModel.setExample("No examples found");
}
models.add(wordModel);
results.add("Word: " + wordModel.getWord() + "\n\n" +
"Definition: " + wordModel.getDefinition() + "\n\n" +
"Example: " + wordModel.getExample());
}
}
}
/*result = "Word: " + wordModel.getWord() + "\n\n" +
"Definition: " + wordModel.getDefinition() + "\n\n" +
"Example: " + wordModel.getExample();*/
} catch (JSONException e) {
count = 50;
}
results.add(url.toString());
return results;
}
Here's the stack trace:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.dictionaryapi.dev/api/v2/entries/ru/мышь
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
at java.base/java.net.URLConnection.getContent(URLConnection.java:749)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:404)
at java.base/java.net.URL.getContent(URL.java:1181)
at DictionaryEntry.getWords(DictionaryEntry.java:73)
at Bot.onUpdateReceived(Bot.java:91)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:321)
+ URLEncoder.encode(message, "UTF-8")
You are sending a HTTP request. The URL should be appropriate for the used encoding.
There are more aspects of using the right charset/encoding, but this might already be sufficient. The site probably uses UTF-8, as that can handle the full Unicode range.
400 is BAD REQUEST.
url = new URL("https://api.dictionaryapi.dev/api/v2/entries/"
+ DictionaryEntry.getLanguage() + "/"
+ URLEncoder.encode(message, "UTF-8"));
And
Scanner in = new Scanner((InputStream) url.getContent(),
StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
while (in.hasNextLine())
{
sb.append(in.nextLine()).append('\n');
}
String result = sb.toString();
Check in your environment that the file was in utf-8u format Because Cyrillic may not be supported
Error message: com.example.myjson W/System.err: org.json.JSONException: Value
of type org.json.JSONObject cannot be converted to JSONArray
JSON is as follows
{
"temp":296.88,
"feels_like":298.86,
"temp_min":296.88,
"temp_max":296.88,
"pressure":1013,
"humidity":89,
"sea_level":1013,
"grnd_level":986
}
I could get data from this alone
String weatherInfo = jsonObject.getString("weather");
Not from this string Why ?
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
String weatherInfo1 = jsonObject.getString("main");
Log.i("weatherMainContent", weatherInfo1);
Log.i("Weather Details" , weatherInfo);
JSONArray jsonArray = new JSONArray(weatherInfo);
JSONArray jsonArray1 = new JSONArray(weatherInfo1);
Log.i("full " , jsonArray1.toString());
String message = "";
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String main = jsonObject1.getString("main");
String description = jsonObject1.getString("description");
Log.i("Weather side Details" , weatherInfo);
Log.i("temperaturerrr", jsonObject1.getString("temp_min"));
String temp_min = jsonObject1.getString("temp_min");
Log.i("temperature", jsonObject1.getString("temp_min"));
String pressure = jsonObject1.getString("pressure");
if (!main.equals("") && !description.equals("") && !temp_min.equals("")) {
message += main + ":" + description +";" + temp_min + "\r\n";
} else {
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
Log.i("Main", jsonObject1.getString("main"));
Log.i("Description", jsonObject1.getString("temp_min"));
}
if (!message.equals("")) {
resultTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "couldn't find the giberish you mentioned :(", Toast.LENGTH_SHORT).show();
}
}
}
Your Json is not an Array, but an Object.
Create a new JSONObject of your Json String.
Then just use the object and use the getDouble("propertyName") method to get the value of the property:
String json = "{\"temp\":296.88,\"feels_like\":298.86,\"temp_min\":296.88,\"temp_max\":296.88,\"pressure\":1013,\"humidity\":89,\"sea_level\":1013,\"grnd_level\":986}";
JSONObject weatherInfo = new JSONObject(json);
double temp = weatherInfo.getDouble("temp");
double feels_like = weatherInfo.getDouble("feels_like");
double temp_min = weatherInfo.getDouble("temp_min");
double temp_max = weatherInfo.getDouble("temp_max");
double pressure = weatherInfo.getDouble("pressure");
double humidity = weatherInfo.getDouble("humidity");
double sea_level = weatherInfo.getDouble("sea_level");
double grnd_level = weatherInfo.getDouble("grnd_level");
System.out.println(temp);
System.out.println(feels_like);
System.out.println(temp_min);
System.out.println(temp_max);
System.out.println(pressure);
System.out.println(humidity);
System.out.println(sea_level);
System.out.println(grnd_level);
If this is your data
"{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200} "
you have to just make some changes in the code to retrieve
String jsonString = "your string";
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("weather");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject weatherObj = jsonArray.getJSONObject(i);
System.out.println(weatherObj);
}
String baseValue = json.getString("base");
Object mainValue = json.get("main");
Object visibilityValue = json.get("visibility");
Object windValue = json.get("wind");
#shivas To retrieve the below json { "main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80} from the source json, kindly check first which property is JSONArray and JSONObject.
Here is the code to retrieve it.
main,wind are JSONObject and weather is a JSONArray.
So assuming sourcejson is the entire JSONObject,
JSONObject main = sourcejson.optJSONObject("main");
System.out.println(main.toString());
JSONObject wind = sourcejson.optJSONObject("wind");
System.out.println(wind.toString());
JSONArray weather = sourcejson.optJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject weatherObj = weather.getJSONObject(i);
System.out.println(weatherObj.toString());
}
String base = sourcejson.optString("base");
int visibility = sourcejson.optInt("visibility");
Try this, you will get your data.
I have code like this, the value of jArrAnswer is
[{"answer":"Yes"},{"answer":"No"},{"answer":"maybe"},{"answer":"yrg"}]
the result from jArrAnswer.length() is 4
but why I got error
org.json.JSONException: Index 1 out of range [0..1).
try {
JSONArray jArrAnswerid = new JSONArray(answerid);
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswerid = jArrAnswerid.getJSONObject(i);
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswerid.getString("answerid");
String ans= jObjAnswer.getString("answer");
GroupModel item2 = new GroupModel(String.valueOf(i + 1), ans, ansid);
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
You are iterating the for loop over jArrAnswer while your fetching the index i over jArrAnswerid.
Check and make sure that the jArrAnswerid.size() is equal to the jArrAnswer.size().
Print the jArrAnswerid.size() and check.
Try this
try {
JSONArray jArrAnswer = new JSONArray(answer);
for (int i = 0; i < jArrAnswer.length(); i++) {
JSONObject jObjAnswer = jArrAnswer.getJSONObject(i);
String ansid = jObjAnswer.getString("answerid");
String ans= jObjAnswer.getString("answer");
}
} catch (Exception e) {
Log.w("asdf", e.toString());
}
provided "answer" is your json array response
Try
String json = "[{\"answer\":\"Yes\",\"answerid\":\"1\"},{\"answer\":\"No\",\"answerid\":\"2\"},{\"answer\":\"maybe\",\"answerid\":\"3\"},{\"answer\":\"yrg\",\"answerid\":\"4\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String answerId = jsonObject.getString("answerid");
String answer = jsonObject.getString("answer");
//Use answerId and answer
}
}
} catch(JSONException e) {
e.printStackTrace();
}
i try to get multiple table from json, i have two tables ( hotline and other ) , i can get data from hotline table, but cannot get from other table
in my php (json):
{"hotline":[{"id":"2","name_hotline":"Tourist Police","phone_hotline":"192"},{"id":"6","name_hotline":"Water","phone_hotline":"1199"}]}{"other":[{"id":"1","name_other":"Lao National Tourism Administration","phone_other":"+85621212248 ","latitude_other":"0","pic_other":"","longtitude_other":"0"},{"id":"2","name_other":"Tourism Police Department","phone_other":"+85621251128 ","latitude_other":"0","pic_other":"","longtitude_other":"0"}]}
MainActivity.java :
InputStream objInputStream = null;
String strJSON = "";
try {
HttpClient objHttpClient = new DefaultHttpClient();
HttpPost objHttpPost = new HttpPost("http://192.168.1.102/emergencycall/php_get_data.php");
HttpResponse objHttpResponse = objHttpClient.execute(objHttpPost);
HttpEntity objHttpEntity = objHttpResponse.getEntity();
objInputStream = objHttpEntity.getContent();
Log.d("Emergency", "Connected HTTP Success !");
} catch (Exception e) {
Log.d("Emergency", "Error Connect to : " + e.toString());
}
try {
BufferedReader objBufferesReader = new BufferedReader(new InputStreamReader(objInputStream, "UTF-8"));
StringBuilder objStrBuilder = new StringBuilder();
String strLine = null;
while ((strLine = objBufferesReader.readLine()) != null) {
objStrBuilder.append(strLine);
}
objInputStream.close();
strJSON = objStrBuilder.toString();
Log.d("Emergency", "Connected JSON Success !");
} catch (Exception e) {
Log.d("Emergency","Error Convert To JSON :" + e.toString() );
}
try {
JSONObject object = new JSONObject(strJSON);
JSONArray objJSONArray = object.getJSONArray("hotline");
JSONArray objJSONAraay2 = object.getJSONArray("other");
for (int i = 0; i < objJSONArray.length(); i++) {
JSONObject objJSONObject = objJSONArray.getJSONObject(i);
strNameHotlineMySQL = objJSONObject.getString("name_hotline");
strPhoneHotlineMySQL = objJSONObject.getString("phone_hotline");
}
for (int j = 0; j < objJSONAraay2.length(); j++) {
JSONObject objJSONObject1 = objJSONAraay2.getJSONObject(j);
strNameHospitalMySQL = objJSONObject1.getString("name_other");
strPhoneHospitalMySQL = objJSONObject1.getString("phone_other");
long insertID4 = objHotlineTable.addDataFromSQLiteHospital(strNameHospitalMySQL, strPhoneHospitalMySQL, strPicHospitalMySQL);
}
} catch (Exception e) {
Log.d("Emergency","Error syncdata to SQLite :" + e.toString() );
}
and i get an error in Logcat:
: Error syncdata to SQLite :org.json.JSONException: No value for other
Your json data format is not correct. Json data format should be like this:
{
"hotline":[
{
"id":"2",
"name_hotline":"Tourist Police",
"phone_hotline":"192"
},
{
"id":"6",
"name_hotline":"Water",
"phone_hotline":"1199"
}
],
"other":[
{
"id":"1",
"name_other":"Lao National Tourism Administration",
"phone_other":"+85621212248 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
},
{
"id":"2",
"name_other":"Tourism Police Department",
"phone_other":"+85621251128 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
}
]
}
And than,
You can use "Retrofit" and "gson" for http request and object mapping.
I am scratching my head to figure out how to parse the following JSON object.
[
{
"result": true,
"response": "Successfully got list of users in radius of 10km"
},
{
"username": "elize",
"photo": "http://www.embedonix.com/apps/mhealth/images/elize/elize.png"
},
{
"username": "mario",
"photo": "http://www.embedonix.com/apps/mhealth/images/mario/mario.png"
}
]
This is I guess a single index json array. The first part tells that the operation of building the json object was ok.
Then there are pairs of username and photo which I have to parse them and put them in a list:
public class User {
private String mName;
private String mPhotoURl;
public User(String name, String url)
{
///
}
}
So if the first entry of json is result -> true I should have a ArrayList<User>.
I tried to do the following but it always raises the JSONParse exception:
try {
JSONObject json = new JSONObject(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONArray obj = json.getJSONArray(String.valueOf(i));
Log.i(TAG, i + " username: " + obj.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Just try this way
try {
JSONArray jsonArray = new JSONArray(data);
int length = jsonArray.length();
for (int i = 1; i < length; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this way,hope this will help you to solve your problem.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
if(i==0){
Log.i(TAG, i + " result: " + obj.getString("result"));
Log.i(TAG, i + " response: " + obj.getString("response"));
}else{
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try Code...something like this..
try {
JSONArray json = new JSONArray(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONObject childObject = json.getJSONObject(i);
if(i==0){
String result = child.getBoolean("result");
String resp = child.getString("response");
} else {
String username = child.getString("username");
String photo = child.getString("photo");
Log.i(TAG, i + " username: " + username);
}
}
} catch (JSONException e) {
e.printStackTrace();
}