Getting simple Json string from url and converting it to String[] Android - java

I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.

you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article

Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.

I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}

What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"

Related

Unable to retrieve data from POST request

I am working in JAVA 1.8 to write and using Apache Tomcat to run the server, I am unable to retrieve data from a POST request i.e in JSON.
I actually need it in an HashMap and I can even parse and convert it into HashMap even if it is readable in JSON. I have tried several links on the internet and I always get exception like Could not deserialize to type interface PACKAGE NAME.
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("ClassifyCase")
public Rules Classify(HttpServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { System.out.println("Buffer Reader Error"); }
System.out.println("What I read: "+jb);
System.out.println("Here la la l ala ");
// System.out.println("Case: ++ "+Case.toString());
System.out.println("Here la la l ala ");
Rules foundRule = new Rules();
// List<Rules> objListRules = new ArrayList<Rules>();
try
{
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
// foundRule = objADBridge.Classify(Case);
logger.info("Classification done!");
}
catch(Exception ex)
{
logger.info("Error in classification");
System.out.println("Couldnt Classify Properly!");
// return
}
return foundRule;
}
Can someone please share a guide on how can I receive this data and convert it into a Map or either I can directly get a Map!
I strongly recommend you to use this library of JSON..
You can find it in Maven Repository and it's so easy to parse a JSON to a Map or to a JSONArray or JSONObject... depends of your necessity what you want to do..
Here is a example show how to parse a JSON to a HashMap
Map<String, Object> map = new JSONObject(--JSONString here--).toMap();
And that's all...
Now, if your JSON has a list of objects, i mean like a list of maps, what you just need to do is this...
JSONArray jsonArray = new JSONArray(--JSON string here--);
for(int i = 0; i < jsonArray.length(); i++){
Map<String, Object> map = jsonArray.getJSONObject(i).toMap();
}
Here is the explanation.
You take you JSON string and pass it as a parameter to the JSONArray,what JSONArray does is, take your json string a parse it to like a list
Then you make a for to get each Object of that list and parse it to a map.
Note: what the JSONObject does, is take the object of the JSONArray and parse it... you can parse it to a map or you can get each object of that map..
String jsonString = "{\n" +
"\t\"1\": \"1\",\n" +
"\t\"FPG\": \"50\",\n" +
"\t\"Symptoms\": \"Yes\"\n" +
"}";
Map<String, String> map = new Gson().fromJson(jsonString, Map.class);
for (String key: map.keySet()) {
System.out.println(map.get(key));
}
The request you send does not contain proper JSON in the body. You are missing the commas ",". It should be something like this:
{
"1":"1",
"FPG":"50",
"Symptoms":"yes"
}
Just change it and give proper JSON format to the message.
Even if the request was not in your control, I would strongly suggest that you contacted the service that creates the message and asked from them to fix it.
It would be the last resort for me to make my own deserializer to handle an "inproper" message.
An easy way to check if your JSON is properly formated is an online formatter, e.g. https://jsonformatter.org/

Parse these Json data with arrays in Android

please tell me I am new to use JSON data. Thanks in Advance.
https://api.myjson.com/bins/waw4y
how to parse this data in android. I am adding the two client details. In that
First, I have added an object for the whole content and after I have added the different client names and age, car with arrays. so please make it as easy.
Thanks in advance
JSON stands for JavaScript Object Notation. It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting
temperature only.
This code is not feasible with dynamic implementation of JSON, Just to showcase the Parsing proccess.
JSONObject client = null;
try {
client = new JSONObject(response);
JSONArray clientChild1 = client.getJSONArray("client1");
JSONArray clientChild2 = client.getJSONArray("client2");
for (int j = 0; j < clientChild1.length(); j++) {
JSONObject objectChild = clientChild1.getJSONObject(j);
Log.e("NAME", "onCreate: " + objectChild.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}

How to get the fields of a JSON object in android studio?

I have an android app and a Web Service. When I want to edit some register I have to get the whole record from the database and put every field in a Edit Text.
The Web Service return me this to the android app
[{"id":"6","0":"6","tipo":"No Oxidado","1":"No Oxidado","fecha":"2015-02-02","2":"2015-02-02","ubicacion":"-1.555505, -6.6171","3":"-1.555505, -6.6171","persona":"Laura Morales","4":"Laura Morales","fotografia":"-","5":"-"}]
And I have a variable called "result" that have this JSON string
How do I put every field in a independent edit text in my Android App?
something like:
txtid.setText(result[0]);
txtType.setText(result[1]);
txtDate.setText(result[2]);
txtLocation.setText(result[3]);
txtPerson.setText(result[4]);
where "result" is my JSON string.
try below code.
if you have more than one json object in array
String response = "[{"id":"6","0":"6","tipo":"No Oxidado","1":"No Oxidado","fecha":"2015-02-02","2":"2015-02-02","ubicacion":"-1.555505, -6.6171","3":"-1.555505, -6.6171","persona":"Laura Morales","4":"Laura Morales","fotografia":"-","5":"-"}]"
try {
JSONArray jsonArray = new JSONArray(response);
for (int i =0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
txtid.setText(jsonObject.getString("0"));
txtType.setText(jsonObject.getString("1"));
txtDate.setText(jsonObject.getString("2"));
}
} catch (JSONException e) {
e.printStackTrace();
}
And if you have only one object in array then no need to use for loop use directly this way
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
txtid.setText(jsonObject.getString("0"));
txtType.setText(jsonObject.getString("1"));
txtDate.setText(jsonObject.getString("2"));
} catch (JSONException e) {
e.printStackTrace();
}
there is a library to convert Json object to android model that call GSON
at first create a model with your input object like below:
class InputModel {
String id;
String 0; //it's better to change this object name
String tipo;
...
}
next, you can use Gson to bind your input to your model. it should be something like this:
InputModel mInput = new Gson().fromJson(data);
ps1: data is your input string
ps2: if you want the name of your input be different with your input name, you can use an annotation like this:
#SerializedName("id")
String productId;

Problem retrieving the earthquake JSON results?

Greeting! After I removed hardcoded JSON data and moved to request data from the URL. I am having an exception error. The code is pretty much the same as the final official git but I am getting the errors.
The code that I am extracting data from JSON is:
private static final String USGS_REQUEST_URL =
"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=5&limit=10";
//
public static List<Earthquake> extractFeaturesfromJson(String earthquakeJSON) {
/*if the json is null then return earlu*/
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
// Create an empty ArrayList that we can start adding earthquakes to
List<Earthquake> earthquakes = new ArrayList<>();
// Try to parse the JsonResponseString. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// create an object form jsonString
JSONObject root = new JSONObject(earthquakeJSON);
JSONArray features = root.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
// Get a single earthquake at position i within the list of earthquakes
JSONObject currentEarthquake = features.getJSONObject(i);
// For a given earthquake, extract the JSONObject associated with the
// key called "properties", which represents a list of all properties
// for that earthquake.
JSONObject properties = currentEarthquake.getJSONObject("properties");
double mag = properties.getDouble("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
//extract the value of key url
String url = properties.getString("url");
//create new object with magnitude, location ane time and url from json response
Earthquake earthquake = new Earthquake(mag, location, time, url);
earthquakes.add(earthquake);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
// Return the list of earthquakes
return earthquakes;
}
The logcat shows:
09-26 14:49:23.628 2551-2584/com.example.android.quakereport E/com.example.android.quakereport.QueryUtils: Problem retrieving the earthquake JSON results.
The json data from your url is not formatted correctly. Compare what you are receiving from the url to the hardcoded data.
This method runs on the main UI thread after the background work has been
completed. This method receives as input, the return value from the doInBackground() method.
First we clear out the adapter, to get rid of earthquake data from a previous
query to USGS.
Then we update the adapter with the new list of earthquakes, which will trigger the ListView to re-populate its list items. But made mistake on populating data to adapter.
#Override
protected void onPostExecute(List<Earthquake> data) {
//clear the adapter of previdous earthquake data
mAdapter.clear();
if (data != null && data.isEmpty()) { //====?????shourld be !data.isEmpty())
mAdapter.addAll(data);
}
}
The real problem was onPostExecute method to populate data in mainthread after do in background method.
If you're taking the Udacity android course and encountering this error for the quakereport/DidUfeelIt app then change the URL and try with some other URL your problem will be solved.
Eg:- The URL provided by during the course was
"http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6"
Then I was getting the same error that is "problem parsing the JSON"
So I tried different URL:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson
And it worked..!!
Always try to get the latest URL's from the USGS website during the course.
Change your request URL to USGS_REQUEST_URL="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=6&limit=10"
The difference is in the use of https instead of http.
According to the API doc of the USGS website this website now uses the HyperText Transfer Protocol Secure (https)
https://earthquake.usgs.gov/fdsnws/event/1/
Use Online Json Validator.
http://jsonlint.com/
they will validate if the json has problems.

Reading JSON file and Writing into a JSON file in Java using selenium Webdriver

I am working on an Automation Framework and I am looking for an alternative for excel to store test data, element locators and page objects.
So one my friend working on Automation is using json file to store all data as its easy and faster in reading and writing data, Also it can be easy in maintaining. They are using ruby as the language.
So I wanted to know if we can do the same using java & selenium to achieve this?
I have searched google for this and it looks like there is a library called "gson" from google, but none that shows how to use it using selenium.
please share your thoughts on this.
Thank you!!
I can't speak to including element locators in a JSON file, as I follow the page object model and include all those in the java classes. However, reading test data from a JSON file is very easy. It's been a while since I've messed around with this, but I used JSON Simple (which I still use to generate JSON objects/files) and did something like this to read in the file:
protected JSONObject getDataFile(String dataFileName) {
String dataFilePath = "src/test/resources/";
JSONObject testObject = null;
try {
FileReader reader = new FileReader(dataFilePath + dataFileName);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
testObject = (JSONObject) jsonObject;
} catch (Exception ex) {
ex.printStackTrace();
}
return testObject;
}
Once you have the JSON Object, JSON simple provides a few different ways to interact with it and get the values. I've played around with Gson a while back and I think that was fairly similar.
I don't know how your data file is/will be structured, but I had a key string that represented a test case name, and the value was a json object that contained other key-value pairs with the actual data and I fed that data to a TestNG data provider. If that is similar to your setup, I can share that code.
EDIT: Here is the method used by the #DataProvider
public Object[][] getTestScenarios(String dataFileName, String testCaseName) {
JSONArray testCase = (JSONArray) getDataFile(dataFileName).get(testCaseName);
List<JSONObject> testScenarioArray = new ArrayList<JSONObject>();
for (int i = 0; i < testCase.size(); i++) {
testScenarioArray.add((JSONObject) testCase.get(i));
}
Object[][] dataProviderArray = new Object[testScenarioArray.size()][];
for (int scenario = 0; scenario < testScenarioArray.size(); scenario++) {
String scenarioName = null;
if ((String) testScenarioArray.get(scenario).get("scenario") != null) {
scenarioName = (String) testScenarioArray.get(scenario).get("scenario");
} else {
scenarioName = "No scenario name specified";
};
dataProviderArray[scenario] = new Object[] { scenarioName, (JSONObject) testScenarioArray.get(scenario) };
}
return dataProviderArray;
}
The scenario name stuff could be removed, as I believe I only used that for logging or reporting, if I recall correctly. The reason I had it as a JSONArray and coded in this fashion is so a single test case could have an array with multiple scenarios with differing data. Didn't want the tests to have to care how many scenarios there were.
I have read a JSON Array from DB and made a list of a JSON object from JSON Array.
The array looks as follows:
[{
"index": "data",
"type": "message",
"sum":
{
"message": "HELLO",
},
}, {
"index": "data",
"type": "message",
"sum":
{
"message": "HELLO123",
}
}]
It is collected from DB in STRING form but is an array as it has SQUARE BRACKETS: [{Json1}, {Json2}].
String data = "ArrayFromDB";
JSONArray jsonArr = new JSONArray(data);
List<String> listJSON = new ArrayList<String>();
for (int i = 0; i < jsonArr.length(); i++)
{
listSMSJSON.add(jsonArr.getJSONObject(i).getJSONObject("sum").getString("message"));
}
System.out.println(listJSON);
listJSON is printed as [HELLO, HELLO123]

Categories

Resources