libgdx Json parsing - java

hi I'm trying to get all 'id' value from my json into my 'results' array.
I didn't really understood how the json class of libgdx works, but I know how json works itself.
Here is the json : http://pastebin.com/qu71EnMx
Here is my code :
Array<Integer> results = new Array<Integer>();
Json jsonObject = new Json(OutputType.json);
JsonReader jsonReader = new JsonReader();
JsonValue jv = null;
JsonValue jv_array = null;
//
try {
String str = jsonObject.toJson(jsonString);
jv = jsonReader.parse(str);
} catch (SerializationException e) {
//show error
}
//
try {
jv_array = jv.get("table");
} catch (SerializationException e) {
//show error
}
//
for (int i = 0; i < jv_array.size; i++) {
//
try {
jv_array.get(i).get("name").asString();
results.add(new sic_PlayerInfos(
jv_array.get(i).get("id").asInt()
));
} catch (SerializationException e) {
//show error
}
}
Here is the error I get : 'Nullpointer' on jv_array.size

Doing it this way will result in a very hacky, not maintainable code. Your JSON file looks very simple but your code is terrible if you parse the whole JSON file yourself. Just imagine how it will look like if you are having more than an id, which is probably going to happen.
The much more clean way is object oriented. Create an object structure, which resembles the structure of your JSON file. In your case this might look like the following:
public class Data {
public Array<TableEntry> table;
}
public class TableEntry {
public int id;
}
Now you can easily deserialize the JSON with libgdx without any custom serializers, because libgdx uses reflection to handle most standard cases.
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
json.setIgnoreUnknownFields(true);
json.setOutputType(OutputType.json);
// I'm using your file as a String here, but you can supply the file as well
Data data = json.fromJson(Data.class, "{\"table\": [{\"id\": 1},{\"id\": 2},{\"id\": 3},{\"id\": 4}]}");
Now you've got a plain old java object (POJO) which contains all the information you need and you can process it however you want.
Array<Integer> results = new Array<Integer>();
for (TableEntry entry : data.table) {
results.add(entry.id);
}
Done. Very clean code and easily extendable.

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/

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

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?"

Printing an object string value located on JSON file using JAVA Jackson

I will keep it simple - trying to print the username ('user') value of this JSON file with JACKSON:
{
"creds" : {
"user": "Y9CJG1756",
"pass": "12222#$1"
},
"env": {
"qa": {
"url": "https://www.walla.com/"
}
}
}
I'm running this function but could only find a way to print the entire string of the object 'creds' instead of just the user name.
public static void isJsonStringWorks(String filePath) {
try {
JsonNode objectValue;
byte[] jsonData = Files.readAllBytes(Paths.get(filePath));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
objectValue = rootNode.get("creds");
System.out.println("object is: " + objectValue + " ,\n" + rootNode);
} catch (Exception e) {
System.out.println("Could not read the JSON file");
}
}
Really appreciate the help.
The correct code would be:
objectValue = rootNode.get("creds").get("user").asText()
Also you shall consider the following options:
Introduce Java representation of your data model and read source JSON string as Java object (using objectMapper.readValue(...) method). After that it will be possible to access values like usual Java beans (root.getCreds().getUser())
Using JsonPath to access "deep" values inside JSON to simplify JSON values lookup. For example creds/user value could be obtained like:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
String value = JsonPath.read(document, "$.creds.user")
you are on right route.
You can call objectValue.get('user')

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;

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