Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have created a Browser class for my project. I now need to extend this project and therefore need to create a suitable test plan and test class.
How do I create this test class?
/**
* Write a description of class Browser here.
*
* #author (johnson)
* #version (10/12/13)
*/
import java.util.ArrayList;
import java.util.List;
public class Browser
{
// instance variables - replace the example below with your own
private int iD;
private String email;
private int yearOfBirth;
private boolean memberID;
private WineCase wineCase;
private boolean loggedIn;
private Website website;
private boolean discount;
private List<Boolean> baskets = new ArrayList<Boolean>();
/**
* Constructor for objects of class Browser
*/
public Browser()
{
// initialise instance variables
wineCase = null;
website = null;
iD = 00065;
yearOfBirth = 1992;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = 0;
email = newEmail;
yearOfBirth = newYearOfBirth;
loggedIn = false;
memberID = true;
discount = false;
}
/**
* Constructor for objects of class Browser
*/
public Browser(int newID, String newEmail,int newYearOfBirth)
{
// initialise instance variables
wineCase = null;
website = null;
iD = newID;
email = newEmail;
yearOfBirth = newYearOfBirth;
memberID = true;
discount = false;
}
/**
* returns the ID
*/
public int getId()
{
return iD;
}
/**
* gets the email of the browser class
*/
public String getEmail()
{
return email;
}
public boolean getDiscount()
{
return discount;
}
/**
* gets the yearOfBirth for the browser class
*/
public int yearOfBirth()
{
return yearOfBirth;
}
public double getWineCost()
{
return wineCase.getWineCost();
}
public double getWineCase()
{
return wineCase.getWineCost();
}
/**
* returns
*/
public void setLoginStatus(boolean status)
{
loggedIn = status;
}
/**
* returns
*/
public void selectWineCase(WineCase winecase)
{
wineCase = winecase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+winecase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
/**
* returns
*/
public void payForWine()
{
website.checkout(this);
}
public void setId()
{
iD = 999;
}
public void setWebSite(Website website)
{
this.website = website;
}
public void setDiscount(boolean discount)
{
this.discount = discount;
}
public ArrayList<WineCase> getBasket(WineCase wineCase)
{
this.wineCase = wineCase;
System.out.println ("Browser "+getId()+" has selcted wine case"+wineCase.getRefNo()+ "of "+wineCase.getNoOfBottles()+ wineCase.getDescription()+ " at £"+wineCase.getWineCost());
}
}
Any answers/replies would be greatly appreciated.
You can use a unit testing framework as http://junit.org/. There are numerous examples on the internet.
An example unit test would be:
public class BrowserTest{
#Test
public void testNoArgsConstructor(){
Browser testedBrowser = new Browser();
assertNull(testedBrowser.getWineCase());
assertNull(testedBrowser.getWebsite());
assertEquals(00065, testedBrowser.getId());
assertEquals(1992, testedBrowser.getYearOfBirth());
assertTrue(testedBrowser.getMemberId());
assertFalse(testedBrowser.isDiscount());
}
//more tests
}
If You want to test your class, use JUnit framework - you will create unit tests (http://junit.org/). It is already included in IDE (Eclipse), just go File → New → JUnit → JUnit Test case.
Related
My project is composition, which a Truck HAS-A Engine which can be called using parameters into the console:
(note, engineStatus represent two arguments which would determine the parameter, IE, One or the other would be inputted; On/Off or True/False)
PrimaTruck truck = new PrimaTruck(150, OUColour.RED, (engineStatus));
I can't think how to get my second class to get the engineStatus() and insert variables properly into the constructor for use with the console command code above. My main error is that it cannot find the engineStatus variable.
I also acknowledge that my code is wrong for the Engine Boolean expressions and can't figure out a good alternative to give engineStatus() an On or Off variable dependant on if engineStart() and engineStop() are On/Off, thus giving a value that can be entered in the PrimaTrucks() constructor parameters.
PrimaTruck.Java
import ou.*;
/**
* Write a description of class PrimaTruck here.
*/
public class PrimaTruck{
// instance variables - replace the example below with your own
private int topSpeed;
private OUColour colour;
public Engine engineStatus;
/**
* Constructor for objects of class PrimaTruck
* Initialise instance variables
*/
public PrimaTruck(int topSpeed, OUColour colour, Engine engineStatus){
this.topSpeed = topSpeed;
this.colour = colour;
this.engineStatus = engineStatus;
}
public void setColour(OUColour aColour){
this.colour = aColour;
}
public OUColour getColour(){
return colour;
}
public int getTopSpeed(){
return topSpeed;
}
}
Engine.Java
/**
* Write a description of class Engine here.
*/
public class Engine{
// instance variables
public Boolean engineStart;
public Boolean engineStop;
public String engineStatus;
private Boolean status;
/**
* Constructor for objects of class Engine
*/
public Engine(String engineStatus){
// initialise instance variables
this.engineStart = engineStart;
this.engineStop = engineStop;
this.engineStatus = engineStatus;
this.status = status;
}
public Boolean status(){
if (engineStart == true){
status = engineStart;
}else if (engineStop = true){;
status = engineStop;
}
return this.status;
}
public Boolean getEngineStart(){
return engineStart;
}
public void setEngineStart(){
this.engineStop = false;
this.engineStart = true;
}
public Boolean getEngineStop(){
return engineStop;
}
public void setEngineStop(){
this.engineStart = false;
this.engineStop = true;
}
public void setEngineStatus(String aStatus){
this.engineStatus = aStatus;
}
public String getEngineStatus(){
return engineStatus;
}
}
Any feedback on coding or pointers on how to implement will be appreciated.
A lot of the code in the Engine class seems redundant. I'm making lot of changes to the code. See whether this is what you want.
public class Engine{
// instance variables
public boolean engineStart;
public boolean engineStop;
public boolean engineStatus;
/**
* Constructor for objects of class Engine
*#param1 - true if engine is started
*#param2 - true if engine is stopped
*#param3 - true if engine is on, else false
*/
public Engine(boolean engineStart, boolean engineStop, boolean engineStatus){
// initialise instance variables
this.engineStart = engineStart;
this.engineStop = engineStop;
this.engineStatus = engineStatus;
}
public boolean getEngineStart(){
return engineStart;
}
public void setEngineStart(){
this.engineStop = false;
this.engineStart = true;
setEngineStatus(true);
}
public boolean getEngineStop(){
return engineStop;
}
public void setEngineStop(){
this.engineStart = false;
this.engineStop = true;
setEngineStatus(false);
}
public void setEngineStatus(boolean engineStatus){
this.engineStatus = engineStatus;
}
public String getEngineStatus(){
return engineStatus;
}
}
This Engine class has only 3 boolean variables: engineStart, engineStop, engineStatus. If engineStart = true, then engineStatus = true. Else engineStatus = false.
I hope this is the functionality you are trying to achieve. Now you need to pass in 3 boolean variables while creating an Engine object.
Now in the truck class make the following changes:
public class PrimaTruck{
// instance variables - replace the example below with your own
private int topSpeed;
private OUColour colour;
public boolean engineStatus;
/**
* Constructor for objects of class PrimaTruck
* Initialise instance variables
*/
public PrimaTruck(int topSpeed, OUColour colour, Engine engine){
this.topSpeed = topSpeed;
this.colour = colour;
this.engineStatus = engine.getEngineStatus();
}
If this is not what you were looking for, feel free to ask in comments.
So I have to create a Bank Simulator project for class, and so far I have a few of the methods implemnted. But currently I am having trouble with the doBusiness method in the ServiceCenter class. Here is the code I have so far.
Main: BankSimulator
import java.util.Scanner;
public class BankSimulator {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("What is the time duration (in minutes) to be simulated? ");
int maxTime = input.nextInt();
System.out.print("What percentage of the time (0-100) does a customer arrive? ");
int arrivalProb = input.nextInt();
ServiceCenter bank = new ServiceCenter();
while (bank.getTime() <= maxTime || bank.customersRemaining()) {
if (bank.getTime() <= maxTime && customerArrived(arrivalProb)) {
bank.addCustomer();
}
bank.doBusiness();
}
//bank.displayStats();
}
private static boolean customerArrived(int prob)
{
return (Math.random()*100 <= prob);
}
}
Server class:
public class Server {
private static int nextID = 1;
private int serverID;
private int endTime;
private Customer serving;
public Server()
{
serverID = nextID;
nextID++;
endTime = 0;
serving = null;
}
/**
* Accessor method for getting the server ID number.
* #return the server ID
*/
public int getID()
{
return serverID;
}
/**
* Assigns a customer to the server and begins the transaction.
* #param c the new customer to be served
* #param time the time at which the transaction begins
*/
public void startCustomer(Customer c, int time)
{
serving = c;
endTime = time + c.getJobLength();
}
/**
* Accessor method for getting the current customer.
* #return the current customer, or null if no customer
*/
public Customer getCustomer()
{
return serving;
}
/**
* Identifies the time at which the server will finish with
* the current customer
* #return time at which transaction will finish, or 0 if no customer
*/
public int busyUntil()
{
return endTime;
}
/**
* Finishes with the current customer and resets the time to completion.
*/
public void finishCustomer()
{
serving = null;
endTime = 0;
}
}
Customer class:
import java.util.Random;
public class Customer {
private static final int MAX_LENGTH = 8;
private static final Random rand = new Random();
private static int nextID = 1;
private int customerID;
private int arrivalTime;
private int jobLength;
/**
* Constructs a customer with the next available ID number,
* the specified arrival time, and a random job length.
* #param arrTime the time at which the customer arrives
*/
public Customer(int arrTime)
{
customerID = nextID;
nextID++;
arrivalTime = arrTime;
jobLength = rand.nextInt(MAX_LENGTH)+1;
}
/**
* Accessor method for getting the customer's ID number.
* #return the customer ID
*/
public int getID()
{
return customerID;
}
/**
* Accessor method for getting the customer's arrival time.
* #return the time at which the customer arrived
*/
public int getArrivalTime()
{
return arrivalTime;
}
/**
* Accessor method for getting the length of the job
* #return the job length (in minutes)
*/
public int getJobLength()
{
return jobLength;
}
}
I had to create the following class called ServiceCenter where getTime returns the time in the simulation which starts at 0 and increments on each step. An addCustomer method where we add a customer to the queue and displayed a message. A customerRemaining which returns true if a customer is currently being waited on. Lastly the doBusiness method which increments the time, if the server finished with a customer remove them from the queue, and if the server is free and there is a customer in the queue, begin serving them. I have the first few ones done except the doBusiness method I am stuck on. Does anyone have any tips?
The code listed above was created by Dave Reed and I take no credit for the code.
ServiceCenter class:
import java.util.LinkedList;
import java.util.Queue;
public class ServiceCenter {
private int arrivalTime, departureTime;
private Queue <Customer> customer;
private Server server;
public ServiceCenter()
{
server = new Server();
customer = new LinkedList <Customer> ();
}
public String addCustomer ()
{
Customer customer1 = new Customer (arrivalTime);
customer.add(customer1);
String result = "" + customer1.getArrivalTime() + "" + customer1.getID() + "" + customer1.getJobLength();
return result;
}
public void doBusiness()
{
if(!customer.isEmpty())
{
if(server == null)
{
customer.remove();
}
}
}
public int getTime()
{
return departureTime - arrivalTime;
}
public boolean customersRemaining()
{
if (!(customer.isEmpty()))
return true;
else
return false;
}
}
Any help at all or tips would be greatly appreciated. I've been trying to figure it out for a week now, but for some reason queues are my weakness. Thanks for reading and sorry for it being so long. Just wanted it to be detailed.
You are using new Customer (arrivalTime); but you don't have the arrivalTime in your constructor of the ServiceCenter-class.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing code for an e-mail system and I have one small problem, I can't figure out how to call a method.
what is the correct way to call the writeAllToFile method in the main method?
public class MailboxSystemSol{
public static void main (String args[]) throws IOException{
//code is too long to post here
}
public static void writeAllToFile(Userlist ul, User u, Message me){
//code is too long to post here
}
}
Here is the UserList class:
/**
* Created by Broomhead0 on 4/11/14.
*/
import java.util.ArrayList;
public class Userlist
{
ArrayList<User> users; //this is an arraylist that will store references to all users
public Userlist()
{
users = new ArrayList<User>();
}
// find a user in the list based on the username
public User findUser(String username)
{
// iterate through the array; only iterate according to how many users are currently in the array
for (int i = 0; i < users.size(); i++)
{
// access the particular user through users.(i), then get the name,
// and call the equals method on that name to compare it with the input username
if (users.get(i).userName.equals(username)){
return users.get(i);
}
}
// no user found
return null;
}
// add a user to the list; only do so if the user does not yet exist
public void addUser(User u)
{
if (findUser(u.userName) != null) //if there is a match,
System.out.println("User already exists");
else //if there is not match
{
users.add(u); //add the username
}
}
//check if this is correct
//accessors
public User getUser(int i){
return users.get(i);
}
public int getNumUsers(){
return users.size();
}
}
Here is the User class:
/**
* Created by Broomhead0 on 4/11/14.
*/
public class User
{
public String userName; // the name of the user
public Mailbox outbox; // reference to the mailbox of sent messages
public Mailbox inbox; // reference to the mailbox of received messages
// create mailboxes according to the size given as input
public User(String o, int boxsize) {
userName = o;
outbox = new Mailbox(boxsize);
inbox = new Mailbox(boxsize);
}
}
Here is the Message class:
/**
* Created by Broomhead0 on 4/11/14.
*/
public class Message {
// the properties of a message
private String sender;
private String receiver;
private String subject;
private String body;
// all property values are known at creation of the message; so initialize
public Message (String s, String r, String sub, String b)
{
sender = s;
receiver = r;
subject = sub;
body = b;
}
// any nice format of printing the names and the values of the properties will do
public void printMsg()
{
System.out.println("Sender: " + sender);
System.out.println("Receiver: " + receiver);
System.out.println("Subject: " + subject);
System.out.println("Message: " + body);
}
// what follows are basic getter methods
public String getSender()
{
return sender;
}
public String getReceiver()
{
return receiver;
}
public String getSubject()
{
return subject;
}
public String getBody()
{
return body;
}
}
public class MailboxSystemSol{
public static void main (String args[]) throws IOException{
//define userlist, user and message variables..
UserList userList = new UserList();
User user = new User("Matthew", 1024);
Message message = new Message("sender#gmail.com", "receiver#gmail.com", "Subject Content", "Body Content");
//do something with declared variables...
writeAllToFile(userList, user, message);
}
public static void writeAllToFile(Userlist ul, User u, Message me){
//code is too long to post here
}
}
hello I get the error message: Missing Method Body Or Declare Abstract, how to fix this, what does this mean?
my code:
public class Mobile
{
// type of phone
private String phonetype;
// size of screen in inches
private int screensize;
// memory card capacity
private int memorycardcapacity;
// name of present service provider
private String mobileServiceProvider;
// type of contract with service provider
private int mobileTypeOfContract;
// camera resolution in megapixels
private int cameraresolution;
// the percentage of charge left on the phone
private int chargeUp;
// wether the phone has GPS or not
private int switchedOnFor;
// to simulate using phone for a period of time
private int charge;
// checks the phones remaining charge
private String provider;
// simulates changing the provider
private String GPS;
// instance variables - replace the example below with your own
private int cost;
// declares cost of the item
// The constructor method
public Mobile(String mobilephonetype, int mobilescreensize,
int mobilememorycardcapacity, String mobileServiceProvider, int mobileTypeOfContract, int mobilecameraresolution, String mobileGPS, int chargeUp,int switchedOnFor, String changeProvider,int getBalance, int cost,int price) {
// initialise the class attributes from the one given as parameters in your constructor.
}
/**
* Other constructor
*/
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
/**
*returns a field price.
*/
public int getcost()
{
return balance;
}
/**
*return the amount of change due for orders of mobiles.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
*/
public void cost (int price)
{
balance = balance + amount;
}
//this.serviceprovider = newserviceprovider;
//this.typeofcontract = 12;
//this.checkcharge = checkcharge;
//this.changeProvider = giffgaff;
//Mobile samsungPhone = new Mobile(
// "Samsung" // String mobilephonetype
//, 1024 // intmobilescreensize
//, 2 // intmobilememorycardcapacity
//, 8 // intmobilecameraresolution
//, "GPS" //String mobileGPS
//, "verizon" // String newserviceprovider
//, "100" // intchargeUp
//, "25" // intswitchedOnFor
//, "25" // intcheckCharge
//, "giffgaff"// String changeProvider
//);
//typeofcontract = 12;
//checkcharge = checkcharge;
//Mutator for newserviceprovider
public void setmobileServiceProvider(String newmobileServiceProvider)
{
mobileServiceProvider = newmobileServiceProvider;
}
//Mutator for contracttype
public void setmobileTypeOfContract(int newmobileTypeOfContract)
{
mobileTypeOfContract = newmobileTypeOfContract;
}
//Mutator for chargeUp
public void setchargeUp(int chargeUp)
{
this.chargeUp = chargeUp;
}
//Mutator to simulate using phone for a period of time
public void switchedOnFor(int switchedOnFor)
{
this.switchedOnFor = switchedOnFor;
}
//Accessor for type of phone
public String getType()
{
return phonetype;
}
//Accessor for provider
public String getprovider()
{
return mobileServiceProvider;
}
//Accessor for contract type
public int getContractType()
{
return mobileTypeOfContract;
}
//Accessor for charge
public int getCharge()
{
return chargeUp;
}
//Accessor which checks the phones remaining charge
public int checkCharge()
{
return checkCharge;
}
// simulates changing the provider
public void changeProvider()
{
provider = changeProvider;
}
//returns the amount of change due for orders of mobiles.
public int Balance()
{
return balance;
}
// A method to display the state of the object to the screen
public void displayMobileDetails() {
System.out.println("phonetype: " + phonetype);
System.out.println("screensize: " + screensize);
System.out.println("memorycardcapacity: " + memorycardcapacity);
System.out.println("cameraresolution: " + cameraresolution);
System.out.println("GPS: " + GPS);
System.out.println("mobileServiceProvider: " + mobileServiceProvider);
System.out.println("mobileTypeOfContract: " + mobileTypeOfContract );
}
/**
* The mymobile class implements an application that
* simply displays "new Mobile!" to the standard output.
*/
public class mymobile {
public void main(String[] args) {
System.out.println("new Mobile!"); //Display the string.
}
}
public static void buildPhones(){
Mobile Samsung = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
Mobile Blackberry = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
}
public static void main(String[] args) {
buildPhones();
}
}
any answers or replies and help would be greatly appreciated as I cant get it to compile like it did before with no syntax errors.
Check constructor declared on line 42. It doesn't have a body.
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Additionally, price and a number of other fields are not declared anywhere.
remove ; from
public Mobile (int cost); {
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Here, you left a semicolon, delete it.
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
I'm trying to get the values out of this JSON string but I'm having a hard time achieving this.
{"DebugLogId":"1750550","RequestId":"17505503","Result":
{"Code":"","DebugLogId":"1750550","Message":""},
"Suggestions":[
{"Ranking":"1","Score":"60","Title":"This is a test message 1"},
{"Ranking":"2","Score":"60","Title":"This is a test message 2"}
]}
What way would be easiest to access the data in 'Suggestions'? I'm using the GSON module. Ideally I would like to put it all in a HashMap.
Thanks for any help and/or suggestions!
Thanks for any help!
Hope this helps:
App.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.Gson;
public class App {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = "{\"DebugLogId\":\"1750550\",\"RequestId\":\"17505503\",\"Result\":{\"Code\":\"\",\"DebugLogId\":\"1750550\",\"Message\":\"\"},\"Suggestions\":[{\"Ranking\":\"1\",\"Score\":\"60\",\"Title\":\"This is a test message 1\"},{\"Ranking\":\"2\",\"Score\":\"60\",\"Title\":\"This is a test message 2\"}]}";
Debug obj = (Debug) gson.fromJson(jsonString, Debug.class);
System.out.println(obj.getSuggestionList().get(1).getTitle());
}
}
Debug.java:
package sg.java.play_sof_json_6596072;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Debug {
#SerializedName("DebugLogId")
private String debugLogId;
#SerializedName("RequestId")
private String requestId;
#SerializedName("Result")
private Result result;
#SerializedName("Suggestions")
private List<Suggestion> suggestionList;
/**
* #return the debugLogId
*/
public final String getDebugLogId() {
return this.debugLogId;
}
/**
* #param debugLogId the debugLogId to set
*/
public final void setDebugLogId(String debugLogId) {
this.debugLogId = debugLogId;
}
/**
* #return the requestId
*/
public final String getRequestId() {
return this.requestId;
}
/**
* #param requestId the requestId to set
*/
public final void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* #return the result
*/
public final Result getResult() {
return this.result;
}
/**
* #param result the result to set
*/
public final void setResult(Result result) {
this.result = result;
}
/**
* #return the suggestionList
*/
public final List<Suggestion> getSuggestionList() {
return this.suggestionList;
}
/**
* #param suggestionList the suggestionList to set
*/
public final void setSuggestionList(List<Suggestion> suggestionList) {
this.suggestionList = suggestionList;
}
}
Result.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("Code")
private String code;
#SerializedName("DebugLogId")
private String debugLogId;
#SerializedName("Message")
private String messahe;
/**
* #return the code
*/
public final String getCode() {
return this.code;
}
/**
* #param code the code to set
*/
public final void setCode(String code) {
this.code = code;
}
/**
* #return the debugLogId
*/
public final String getDebugLogId() {
return this.debugLogId;
}
/**
* #param debugLogId the debugLogId to set
*/
public final void setDebugLogId(String debugLogId) {
this.debugLogId = debugLogId;
}
/**
* #return the messahe
*/
public final String getMessahe() {
return this.messahe;
}
/**
* #param messahe the messahe to set
*/
public final void setMessahe(String messahe) {
this.messahe = messahe;
}
}
Suggestion.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.annotations.SerializedName;
public class Suggestion {
#SerializedName("Ranking")
private String ranking;
#SerializedName("Score")
private String score;
#SerializedName("Title")
private String title;
/**
* #return the ranking
*/
public final String getRanking() {
return this.ranking;
}
/**
* #param ranking the ranking to set
*/
public final void setRanking(String ranking) {
this.ranking = ranking;
}
/**
* #return the score
*/
public final String getScore() {
return this.score;
}
/**
* #param score the score to set
*/
public final void setScore(String score) {
this.score = score;
}
/**
* #return the title
*/
public final String getTitle() {
return this.title;
}
/**
* #param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
}
I'm recommend you to use flexjson library http://flexjson.sourceforge.net/
IMHO, it more simple and usable library. I has used GSON first time, but then switched all my projects to flexjson instead of GSON.
Using the standard json classes in android:
JSONObject o = new JSONObject("your string");
JSONArray a = o.getJSONArray("Suggestions");
int i = 0;
while ( i < a.length())
{
o = a.getJSONObject(i);
//do something with o, like o.getString("Title") ...
++i;
}
Ideally I would like to put it all in a HashMap.
If you can switch libraries, Jackson can achieve that with just one line of code.
Map map = new ObjectMapper().readValue(json, Map.class);
This would deserialize any JSON object into a HashMap, composed of just Java SE components. I haven't yet seen another Java-to/from-JSON library that can do that.
The same can be accomplished with Gson, but it requires a few more lines of code. Here's one such solution.
JsonElement je = new JsonParser().parse(json);
JsonObject jo = je.getAsJsonObject();
Map<String, Object> map = createMapFromJsonObject(jo);
// ...
static Map<String, Object> createMapFromJsonObject(
JsonObject jo)
{
Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, JsonElement> entry : jo.entrySet())
{
String key = entry.getKey();
JsonElement value = entry.getValue();
map.put(key, getValueFromJsonElement(value));
}
return map;
}
static Object getValueFromJsonElement(JsonElement je)
{
if (je.isJsonObject())
{
return createMapFromJsonObject(je.getAsJsonObject());
}
else if (je.isJsonArray())
{
JsonArray array = je.getAsJsonArray();
List<Object> list = new ArrayList<Object>(array.size());
for (JsonElement element : array)
{
list.add(getValueFromJsonElement(element));
}
return list;
}
else if (je.isJsonNull())
{
return null;
}
else // must be primitive
{
JsonPrimitive p = je.getAsJsonPrimitive();
if (p.isBoolean()) return p.getAsBoolean();
if (p.isString()) return p.getAsString();
// else p is number, but don't know what kind
String s = p.getAsString();
try
{
return new BigInteger(s);
}
catch (NumberFormatException e)
{
// must be a decimal
return new BigDecimal(s);
}
}
}
(I copied this code from my blog post at http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html.)