Read out from another method - java

So I got this piece of code:
public static ArrayList<Vehicle> readVehicles() throws IOException {
ArrayList<Vehicle> out = new ArrayList<Vehicle>();
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("Vehicles.json"));
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray jsonvehicles = (JSONArray) jsonObject.get("Vehicles");
Iterator i = jsonvehicles.iterator();
while (i.hasNext()) {
JSONObject v = (JSONObject) i.next();
/*
* Engines(); Chassis(); Tires();
*/
// out.add(new Vehicle(...);
}
return out;
}
public static ArrayList<Engine> readEngines() throws IOException {
ArrayList<Engine> out = new ArrayList<Engine>();
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("Engines.json"));
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray jsonengines = (JSONArray) jsonObject.get("Engines");
Iterator i = jsonengines.iterator();
while (i.hasNext()) {
JSONObject v = (JSONObject) i.next();
String name = (String) v.get("name");
int price = (int) v.get("price");
int quality = (int) v.get("quality");
int maxSpeed = (int) v.get("maxSpeed");
int maxAccelaration = (int) v.get("maxAcceleration");
out.add(new Engine(name, price, quality, maxSpeed, maxAccelaration));
}
return out;
}
and so on, regarding at tires(), and chassis.
My question is, how do I get the output of for example, engine, into vehicle?
See, a vehicle consists of engines, chassis and tires. And a engine as the properties quality, name, price and so on. How do I kinda add this to a new vehicle?
It's probably already been asked, but I really don't know how to ask this (native language isn't English). Sorry if I sound really vague, but to be honest, I'm not sure what I'm asking.

As Kevin Esche said, you can do it by something like this (For example) :
Car.java class file
private class Car{
private Engine engine;
private ArrayList<Tire> tires;
public void setEngine(Engine carEngine){
this.engine = carEngine;
}
public Engine getEngine(){
return this.engine;
}
public void addTire(Tire carTire){
this.tires.add(carTire);
}
}
Engin java class file
private class Engine{
private int horsepower;
public int getHorsepower() {
return horsepower;
}
public void setHorsepower(int horsepower) {
this.horsepower = horsepower;
}
}
Tire.java file
private class Tire{
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
In addition, something is missing in your "readVehicle()" method code.
You need to write how to build a Vehicule from your Json Object.
So if your json file looks like :
{
"carType": "Mercedes Classe B"
}
you will need to write in your code (readVehicle() method for example):
Vehicule vehicule = new Vehicle();
vehicule.setType(object.getString("carType"));

Related

Getting value from json item in java

I have a json file, for example:
{
"A":"-0.4",
"B":"-0.2",
"C":"-0.2",
"D":"X",
"E":"0.2",
"F":"0.2",
"J":"0.3"
}
I want return each element of a list json when I call it via my function.
I did a function to do this:
public JSONObject my_function() {
JSONParser parser = new JSONParser();
List<JSONObject> records = new ArrayList<JSONObject>();
try (FileReader reader = new FileReader("File.json")) {
//Read JSON file
Object obj = parser.parse(reader);
JSONObject docs = (JSONObject) obj;
LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}
for (int i = 0; i < docs.size(); i++) {
records.add((JSONObject) docs.get(i));
System.out.println((records)); // it return null
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
LOGGER.info("The first element of a list is:" +records.get(0)); // return null
return records.get(0);
How can I change my function to return the value of each element in a json file.
For example, when I call my_function:
my_function.get("A") should display -0.4
Thank you
First you need a Class for mapping
public class Json {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;
//getters and setters
}
Then in your working class
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);
then you can use that object in a usual way...
here is the dependency I used
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Reference
In Java you can use only class`s methods, as I know.
If you want to get your second element by its first, you should in your class create 2 methods like
class Main {
Map<String, String> records = new HashMap<>();
public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}
public String get(String firstElement){
return map.getValue(firstElement);
}
}
class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");
}

Split jsonarray data into multiple list using array value

I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance
You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;

Dealing with different JSONArray types

I have a program that reads in a simple JSON file and manipulates the data. I then store this data in trees (albeit badly). I have a problem where arguments can longs e.g {1,2}, longs and variables e.g {1,x2}, or variables with other variables e.g. {x1,x2}.
I have been able to retrieve the variables from the JSONArray. The problem arises when I have a variable and a value. I can't for the life of me figure out how to deal with such an occurrence. I apologise for the excessive use of try-catch operations. If anyone could help me solve this issue, it would be much appreciated.
public class program {
public static void main(String[] args) throws IOException {
File file = new File();
File outputfile = new File();
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter(outputfile, true)));
JSONParser parser = new JSONParser();
try {
// creates object of parsed file
Object object = parser.parse(new FileReader(file));
// casts object to jsonObject
JSONObject jsonObject = (JSONObject) object;
// gets declaration-list JSONArray from the object created.
JSONArray jsonArray = (JSONArray) jsonObject.get("declaration-list");
// Surrounding this in a try-catch would allow me to deal with the
// different value cases unlike the frist time i wrote it
try {
/*
* iterator to cycle through the array. Made the mistake last
* time of continuously calling a method
*/
Iterator iterator = jsonArray.iterator();
while (iterator.hasNext()) {
JSONObject jo = (JSONObject) iterator.next();
String variableName = (String) jo.get("declared-variable");
MyTreeNode<String> root = new MyTreeNode<>(variableName);
try {
long value = (long) jo.get("value");
MyTreeNode<Long> child1 = new MyTreeNode(value);
System.out.println(root.getData());
root.addChild(child1);
for (MyTreeNode node : root.getChildren()) {
System.out.println(node.getData());
}
test.put(variableName, value);
// numPrint(test, variableName, pw);
} catch (Exception e) {
final JSONObject jsonValue = (JSONObject) jo.get("value");
final String operator = (String) jsonValue.get("operator");
final JSONArray arguments = (JSONArray) jsonValue.get("arguments");
ArrayList values[] = new ArrayList[arguments.size()];
if (operator.equals("set")) {
for(int i = 0; i < arguments.size(); i++){
try{
//prints nested variables
JSONObject jtest = (JSONObject) arguments.get(i);
String varval = (String) jtest.get("variable");
System.out.println(varval);
}catch(Exception g){
}
}
MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
root.addChild(test1);
for (MyTreeNode node : root.getChildren()) {
System.out.print(root.getData());
System.out.print(" = ");
System.out.println(node.getData());
}
}
if (operator.equals("pair")) {
MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
root.addChild(test1);
for (MyTreeNode node : root.getChildren()) {
System.out.print(root.getData() + " = ");
System.out.println(node.getData());
}
}
}
}
} catch (Exception e) {
System.out.println("oops");
}
} catch (FileNotFoundException e) {
System.out.println("Input file not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
System.out.println("File was not parsed");
e.printStackTrace();
}
pw.flush();
pw.close();
}
}
class MyTreeNode<T> {
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
newChild.setParent(this);
children.add(newChild);
}
public void addChildren(List<MyTreeNode> children) {
for (MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode parent) {
this.parent = parent;
}
public MyTreeNode getParent() {
return parent;
}
}
class myObject {
String operator;
JSONArray arguments;
public myObject(String operator, JSONArray arguments) {
this.operator = operator;
this.arguments = arguments;
}
public JSONArray get() {
return arguments;
}
public String toString() {
if (arguments.size() == 0) {
return "{}";
}
if (operator.equals("pair")) {
return "(" + arguments.get(0) + "," + arguments.get(1) + ")";
} else if (operator.equals("set")) {
String concat = "{" + arguments.get(0);
for (int i = 1; i < arguments.size(); i++) {
concat += "," + arguments.get(i);
}
return concat += "}";
}
return "wot";
}
}
In order to process the JSONArray, I suggest that you create a method which checks the type of the object first and then delegates the processing to other specialised methods based on its type.
This will allow you re-use the code in case you have arrays in arrays and also to navigate through the JSON tree.
Something along these lines:
private static void processArray(JSONArray jsonArray) {
jsonArray.forEach(o -> {
if (o instanceof Number) {
processNumber((Number) o);
} else if (o instanceof JSONObject) {
process((JSONObject) o);
} else if (o instanceof String) {
process((String) o);
} else if (o instanceof JSONArray) {
processArray((JSONArray) o); // recursive call here.
}
});
}
Other methods would look like:
private static void process(String o) {
System.out.println(o); // just an example
}
public static void processNumber(Number number) {
System.out.println(number); // just an example
}
And the most complex would be the one for processing objects:
private static void process(JSONObject o) {
o.forEach((s, o1) -> {
System.out.println(s);
if (o1 instanceof Number) {
processNumber((Number) o1);
} else if (o1 instanceof JSONObject) {
process((JSONObject) o1); // recursion
} else if (o1 instanceof String) {
process((String) o1);
} else if (o1 instanceof JSONArray) {
processArray((JSONArray) o1);
}
});
}
This method would also be recursive. With this type of approach you can navigate through all objects in the tree.
Update:
If you want to process JSON like:
{
"declared-variable": "x17",
"value": {
"operator": "set",
"arguments": [
1,
2,
{
"variable": "x8"
}
]
}
}
you can do so by creating a main method similar to this one:
public static void main(String[] args) throws IOException, ParseException {
JSONParser jsonParser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("array_mixed.json")) {
Object obj = jsonParser.parse(in);
if (obj instanceof JSONArray) {
processArray((JSONArray) obj);
}
else if(obj instanceof Object) {
process((JSONObject) obj);
}
}
}
This main method together with the other methods described can at least print out all the elements in the JSON.
You should be able to at least print out the following in the case of the specified JSON above:
declared-variable
x17
value
arguments
1
2
variable
x8
operator
set

Extract JSON Keynames in Java

I want to extract JSON structure (only keyNames structure) by preserving the hierarchy (parent child relationship); I don't want values from the JSON yet.
I am new to Java and have been tying to achieve this using Jackson , but with no success.
Any direction on this will be much appreciated.
I created a static inner class for you by using JSONObject (http://www.json.org/javadoc/org/json/JSONObject.html)
public static class KeyNode {
private String name;
private ArrayList<KeyNode> children;
public KeyNode(String name) {
this.name = name;
this.children = new ArrayList<KeyNode>();
}
public void addChild(KeyNode child) {
this.children.add(child);
}
public static void parseJsonToKeys(KeyNode node, JSONObject json) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String name = (String) keys.next();
KeyNode child = new KeyNode(name);
node.addChild(child);
if (json.optJSONObject(name) != null) {
parseJsonToKeys(child, json.getJSONObject(name));
} else if (json.optJSONArray(name) != null) {
JSONArray array = json.getJSONArray(name);
for (int i = 0; i < array.length(); i++) {
try {
array.getJSONObject(i);
parseJsonToKeys(child, json.getJSONObject(name));
} catch (JSONException e) {
// this is ok
}
}
}
}
}
public static void exampleCodeUsage() {
try {
JSONObject json = new JSONObject("your json");
KeyNode keyHierarchy = new KeyNode("root");
parseJsonToKeys(keyHierarchy, json);
} catch (JSONException e) {
// your json is not formatted correctly
}
}
}
JSONParser parser = parser;
Object obj = parser.parse(new FileReader(FileName.Json));
JSONObject jobj = (JSONObject) obj;
obj.keys()
The method will give you the list of all keys in JSONObject

How can i use a constructor of a generic class

i got multiple classes which do basicly the same. I pass a JSONObject in the constructor an it sets some variabes.
Now i got some other classes which create those first classes and add them to a ArrayList. Now i want to merge the second classes to one using generics.
This is what I want to do:
public class Data<T> {
public ArrayList<T> data;
public Data(String response1) {
data = new ArrayList<T>();
JSONArray ja;
try {
ja = new JSONArray(response1);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
data.add(new T(jo));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
but it doesnt let me create an Instance of T with
new T(jo);
Would be nice if someone can help me
There is a standard trick for this situations: pass Class<T> along with the String data into the call, and add a setter for the JSONObject. This would let you call a parameterless constructor, like this:
interface WithJson {
void setJson(JSONObject jo);
}
public class Data<T extends WithJson> {
public Data(String response1, Class<T> type) {
data = new ArrayList<T>();
JSONArray ja;
try {
ja = new JSONArray(response1);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
T obj = type.newInstance();
object.setJson(jo);
data.add(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The Class<T> has been modified in Java 5 to let you use it as a factory for the instances of that class. The call of type.newInstance is checked statically for type safety. The addition of the interface WithJson lets you call setJson method on the instances of T in a way that the compiler can check statically.
When you construct Data<T>, you need to pass the class being created, like this:
Data<MyContent> d = new Data(jsonString, MyContent.class);
Use a generic factory interface.
public interface Factory<T>
{
public T createFromJSONObject( JSONObject jo );
}
And now a modified constructor:
public Data(
String response1,
Factory<T> factory
) {
data = new ArrayList<T>();
JSONArray ja;
try {
ja = new JSONArray(response1);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
data.add( factory.createFromJSONObject( jo ) );
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Categories