Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");
;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
root.put("issue", issue);
finaljson.put(root);
}
System.out.println("JSON DATA" + finaljson.toString());
Hey Making a JSON,as from the code if user will enter versionname is multiple time that it should not add in root jsonobject. so how to restrict it.
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "ekey1"
}
],
"versionName": "v1"
},
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
but want
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "eky1"
},
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
can you help me how to make this type of dynamic json data
If I understand correctly, you want the output to be like the second JSON array in your question. Changing where you loop should do the trick:
Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
}
root.put("issue", issue);
finaljson.put(root);
System.out.println("JSON DATA" + finaljson.toString());
I tested with the input you have. Here is the formatted JSON output:
[
{
"issue": [
{
"epickKey": "eky1",
"epickName": "e1"
},
{
"epickKey": "eky2",
"epickName": "e2"
}
],
"versionName": "vkey1",
"versionKey": "v1"
}
]
Read in your json using Gson:
Define Pojos for your Json Objects:
public class Epic {
String versionKey, versionName;
Issue issue;
}
public class Issue{
String epicName, epicKey;
}
Load Pojos from json using Gson
// Create gson object
Gson gson = new GsonBuilder().create();
// Load your json objects:
BufferedReader br = new BufferedReader(new FileReader("file.json"));
List<Epic> epics = gson.fromJson(br, new TypeToken<ArrayList<Epic>>() {}.getType());
Create the class structure you want for your "multi-issue-epics":
// This will be used to store in the format you want
public class MultiIssueEpic{
public String versionKey, versionName;
public Set<Issue> issueSet;
public MultiIssueEpic(Epic epic){
this.versionName = epic.versionName;
this.versionKey = epic.versionKey;
this.issueSet = new HashSet<>();
this.issueSet.add(epic.issue);
}
}
Build the MultiIssueEpic up from your List<Epic>:
Map<String, MultiIssueEpic> epicMap = new HashMap<>();
for(Epic epic : epics){
if(epicMap.contains(epic.versionName)){
// Add issue to existing MultiIssueEpic
epicMap.get(epic.versionName).issueSet.add(epic.issue);
} else{
// Add new MultiIssueEpic
epicMap.put(epic.versionName, new MultiIssueEpic(epic));
}
}
// Here is your list of MultiIssueEpics:
List<MultiIssueEpic> multiIssueEpics = new ArrayList<>(epicMap.values());
I change your code and I add two other class. One named Data for (versionKey, nameKey), the second one Epic for (epickName,epickKey)
and to generate Json, I use Gson lib.
This code :
Epic Class:
public class Epic {
private String epicName;
private String epicKey;
public Epic() {
}
public Epic(String epicName, String epicKey) {
this.epicName = epicName;
this.epicKey = epicKey;
}
public String getEpicName() {
return epicName;
}
public void setEpicName(String epicName) {
this.epicName = epicName;
}
public String getEpicKey() {
return epicKey;
}
public void setEpicKey(String epicKey) {
this.epicKey = epicKey;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Epic [epicName=");
builder.append(epicName);
builder.append(", epicKey=");
builder.append(epicKey);
builder.append("]");
return builder.toString();
}
}
Data Class :
import java.util.List;
public class Data {
private String versionName;
private String versionKey;
private List<Epic> epics;
public Data() {
}
public Data(String versionName, String versionKey, List<Epic> epics) {
this.versionName = versionName;
this.versionKey = versionKey;
this.epics = epics;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getVersionKey() {
return versionKey;
}
public void setVersionKey(String versionKey) {
this.versionKey = versionKey;
}
public List<Epic> getEpics() {
return epics;
}
public void setEpics(List<Epic> epics) {
this.epics = epics;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((versionKey == null) ? 0 : versionKey.hashCode());
result = prime * result
+ ((versionName == null) ? 0 : versionName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Data other = (Data) obj;
if (versionKey == null) {
if (other.versionKey != null)
return false;
} else if (!versionKey.equals(other.versionKey))
return false;
if (versionName == null) {
if (other.versionName != null)
return false;
} else if (!versionName.equals(other.versionName))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Data [versionName=");
builder.append(versionName);
builder.append(", versionKey=");
builder.append(versionKey);
builder.append(", epics=");
builder.append(epics);
builder.append("]");
return builder.toString();
}
}
Main Class:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Data> datas = new ArrayList<Data>();
boolean add = false;
for (int j = 0; j < 2; j++) {
add = false;
Data data = new Data();
System.out.println("Enter Version Name");
data.setVersionName(input.next());
System.out.println("Enter Version Key");
data.setVersionKey(input.next());
Epic epic = new Epic();
System.out.println("Enter Epic Name");
epic.setEpicName(input.next());
System.out.println("Enter Epic Key");
epic.setEpicKey(input.next());
List<Epic> epics = new ArrayList<Epic>();
if(datas.isEmpty()){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}else{
for(Data d:datas){
if(d.equals(data)){
d.getEpics().add(epic);
add=true;
}
}
if(!add){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}
}
}
//Gson gson = new GsonBuilder().setPrettyPrinting().create();
//System.out.println(gson.toJson(datas));
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(datas);
System.out.println(jsonArray.toString());
}
}
PS: Url to download Gson API
Edit
I made a change in the Main Class to use json-lib-2.4-jdk15.jar
Take a look at this URL:
json-lib
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
i have problem to parse my json data,
this is my json data :
{"data":
[
{"ean": "222222","itemname": "","location": "001010202,001010201","po":[
{"ponumber": 1,"qty": 22
},
{"ponumber": 2,"qty": 33
}
]
},
{
"ean": "11112222",
"itemname": "เหงือก",
"location": "001010601",
"po": [
{
"ponumber": 1,
"qty": 7
}
]
},
{
"ean": "22223333",
"itemname": "Crystal Water",
"location": "001010410,001010401",
"po": [
{
"ponumber": 3,
"qty": 13
}
]
}
]}
i want to show the output like :
thank you
this is my java code to parsing json data and show to listview :
void parseJsonData(String jsonString) throws JSONException {
String data = "";
String data2 = null;
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname +"\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++ ) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2 = "\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n";
list.add(data+data2);
System.err.println(data+data2);
}
}
ArrayAdapter<String> LVarray;
LVarray = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(LVarray);
}
this is screen shot the output:
1.You can use StringBuilder to save the data2(po List).
2.In the inner for loop ,you can use append method to add it in it .
3.Get the length of StringBuilder .Then remove the saved data2.
4.Then you can save again .
Edit
public void parseJsonData(String jsonString) throws JSONException {
String data = "";
StringBuilder data2 = new StringBuilder();
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname + "\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2.append("\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n");
list.add(data + data2);
}
System.err.println(data + data2);
int sb_length = data2.length();
data2.delete(0, sb_length);
}
}
this also can help
try {
//Get root array
JSONArray data_array = jsonObject.getJSONArray("data");
for (int i=0;i<data_array.length();i++){
JSONObject jsonObject1 = array.getJSONObject(i);
String ean = jsonObject1.optString("ean");
String itemname = jsonObject1.optString("itemname");
String location = jsonObject1.optString("location");
JSONArray child_Array = jsonObject1.getJSONArray("po");
for (int j=0;j<childArray.length();j++){
JSONObject childJosnObject = array.getJSONObject(i);
String ponumber = jsonObject1.optString("ponumber");
String qty = jsonObject1.optString("qty");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You have to try like this, it will help you
JsonParseModel jsonParseModel = new Gson().fromJson(jsonString,JsonParseModel.class);
public class JsonParseModel {
private ArrayList<DataClass> data;
public ArrayList<DataClass> getData() {
return data;
}
public void setData(ArrayList<DataClass> data) {
this.data = data;
}
public class DataClass{
private String ean,itemname,location;
private ArrayList<PoData> po;
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ArrayList<PoData> getPo() {
return po;
}
public void setPo(ArrayList<PoData> po) {
this.po = po;
}
public class PoData{
private int ponumber,qty;
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
}
}
private void parseJsondata(String response) {
try {
// response
JSONObject jsonObject = new JSONObject(response);
// get data from JSONArray
JSONArray data = jsonObject.getJSONArray("data");
// for loop to your JSONArray's Strings
for (int i = 0; i < data.length(); i++) {
// get JSONObject from i
JSONObject jo = data.getJSONObject(i);
// get string
String ean = jo.getString("ean");
String itemname = jo.getString("itemname");
String location = jo.getString("location");
JSONArray jA = jo.getJSONArray("po");
for (int j = 0; j < jA.length(); j++) {
// get JSONObject by jO
JSONObject jO = jA.getJSONObject(i);
// get string
String ponumber = jO.getString("ponumber");
String qty = jO.getString("qty");
}
}
//Log response
Log.e("response:", response);
} catch (JSONException e) {
e.printStackTrace();
}
}
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
System.out.println("Sentence is:: " + s);
System.out.println("Id is:: " + id);
System.out.println("text file is:: " + txtFile);
}
} catch (JSONException e) {
e.printStackTrace();
}
currently, the above code is able to print out all the records. However, I would like to change the system.out.println into return variables such as return ID, return txtFile, return sentence. How to do that?
Create an Object. use an arraylist to store your object and use it later.
public class myItem{
String sentence;
int id;
String txtfile;
public myItem(){
}
public String getSentence(){
return sentence;
}
public setSentence(String s){
this.sentence = sentence;
}
}
public void yourFunction(){
try {
ArrayList <myItem> myList = new ArrayList();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i =0; i < result.length(); i++){
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
myItem newItem = new myItem();
newItem.setSentence(s);
myList.add(newItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I agree with what Zhi Kai said in the comment.
PS. I can't comment yet so I'm writing this as an answer.
Create a POJO and u se data structure. In your case you are using a for loop so I assume you need to return a list of values from your JSONArray.
Here's what you can do.
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
Updated:
public class YourObject {
private String id;
private String txtFile;
private String sentence;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTxtFile() {
return txtFile;
}
public void setTxtFile(String txtFile) {
this.txtFile = txtFile;
}
public String getSentence() {
return sentence;
}
public void setSentence(String sentence) {
this.sentence = sentence;
}
}
public List<YourObject> returnObject(){
String jsonString = readJsonFile(filePath);
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
List<YourObject> yourObjectToReturn = new ArrayList<YourObject>();
for (int i = 0; i < result.length(); i++) {
YourObject yourObject = new YourObject();
JSONObject j = result.getJSONObject(i);
String s = j.getString("sentence");
int id = j.getInt("id");
String txtFile = j.getString("txtfile");
yourObject.setId(id);
yourObject.setTxtFile(txtFile);
yourObject.setSentence(s);
yourObjectToReturn.add(yourObject);
}
return yourObjectToReturn;
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm trying to read JSON file in Java (I'm starting with JSON).
The JSON file:
[
{
"idProducto":1,
"Nombre":"Coca Cola",
"Precio":0.9,
"Cantidad":19
},
{
"idProducto":2,
"Nombre":"Coca Cola Zero",
"Precio":0.6,
"Cantidad":19
},
[....]
]
I tried the following:
ArrayList<Dispensador> Productos = new ArrayList<Dispensador>();
FileReader reader = new FileReader(new File("productos.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
Long idProducto = (Long) object.get("idProducto");
JSONArray nombres = object.getJSONArray("idProducto");
Iterator i = jsonArray.iterator();
while (i.hasNext()) {
String nombre = (String) object.get("Nombre");
Double precio = (Double) object.get("Precio");
BigDecimal precioB = new BigDecimal(precio);
Long cantidad = (Long) object.get("Cantidad");
int cantidadB = toIntExact(cantidad);
System.out.println(nombre);
Productos.add(new Dispensador(nombre, precioB, cantidadB));
}
But enters into loop. Also I tried with a for loop, but no luck.
Thanks!
You can use gson library
You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/gson
package com.test;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class AppJsonTest {
public static void main(String[] args) {
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>() {
}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i = 0; i < inpList.size(); i++) {
DataObject x = inpList.get(i);
System.out.println(x.toString());
}
}
}
class DataObject {
int idProducto;
String Nombre;
Double Precio;
int Cantidad;
public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
this.idProducto = idProducto;
Nombre = nombre;
Precio = precio;
Cantidad = cantidad;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public Double getPrecio() {
return Precio;
}
public void setPrecio(Double precio) {
Precio = precio;
}
public int getCantidad() {
return Cantidad;
}
public void setCantidad(int cantidad) {
Cantidad = cantidad;
}
#Override
public String toString() {
return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
}
}
Use gson library to read and write json:
try {
JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("idProducto")) {
System.out.println(reader.nextInt());
} else if (name.equals("Nombre")) {
System.out.println(reader.nextString());
} else if (name.equals("Precio")) {
System.out.println(reader.nextDouble());
} else if (name.equals("Cantidad")) {
System.out.println(reader.nextInt());
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip
You are testing whether the iterator has a next element with i.hasNext(). But you don't consume (or retrieve) this next element by i.next() which is typically in the first statement of the looped block. Therefore i.hasNext() will return true forever.
EDIT: You probably want to set object to i.next() because in your code snippet it always remains at the 0's element you assigned before the loop.
There are many open source libraries, present to parse json to object or just to read and write json values. If you want to read and write json then you can use org.json library.
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
String id = jsonObj.getString("pageInfo");
You can see complete example here :-
How to parse Json in java
If you want to parse your json to particular POJO and then use that pojo to get values, then use jackson-databind library, this will parse your json to POJO class :-
ObjectMapper mapper = new ObjectMapper();
book = mapper.readValue(json, Book.class);
You can see complete example here, How to parse json in java
My program prints out a library. Each library is composed of books. Each book is composed of a title and the authors of that book. I have a driver program, a Library class, and a Book class. My issue is that when I use my driver program that uses my toString() methods in the library and book classes to print the library, the authors of each book are appearing as [author, ;, author, ;, author] and I want them to print as author; author; author.
Expected output: http://prntscr.com/810ik2
My output: http://prntscr.com/810ipp
My input: http://prntscr.com/810j6f
getAuthors is the method in my driver program that separates the authors (In the input file that the authors are taken from authors are separated by '*' instead of separated by ';' which is what i need in my output)
Please let me know in the comments if there is too little info, too much info, if what I've given is too confusing, or if I didn't explain anything properly. I'm new to Java and fairly new at posting questions here so please go easy on me. Thank you!
Edit: Just in case here are my three classes (only the important stuff):
Book.java:
import java.util.*;
public class Book implements Comparable<Book>
{
private final String myTitle;
private final ArrayList<String> myAuthors;
public Book(final String theTitle, final ArrayList<String> theAuthors)
{
if (theTitle == "" || theAuthors.isEmpty() ||
theTitle == null || theAuthors.get(0) == null)
{
throw new IllegalArgumentException(
"The book must have a valid title AND author.");
}
else
{
myTitle = theTitle;
myAuthors = new ArrayList<String>();
for (int i = 0; i < theAuthors.size(); i++)
{
myAuthors.add(theAuthors.get(i));
}
}
}
public String toString()
{
String result = "\"" + myTitle + "\" by ";
for (int i = 0; i < myAuthors.size(); i++)
{
result += (String)myAuthors.get(i);
}
return result;
}
}
Library.java:
import java.util.*;
public class Library
{
public Library(final ArrayList<Book> theOther)
{
if (theOther == null)
{
throw new NullPointerException();
}
else
{
myBooks = new ArrayList<Book>();
for (int i = 0; i < theOther.size(); i++)
{
myBooks.add(theOther.get(i));
}
}
}
public ArrayList<Book> findTitles(final String theTitle)
{
ArrayList<Book> titleList = new ArrayList<Book>();
for (int i = 0; i < myBooks.size(); i++)
{
if (myBooks.get(i).getTitle().equals(theTitle))
{
titleList.add(myBooks.get(i));
}
}
return titleList;
}
public String toString()
{
String result = "";
for (int i = 0; i < myBooks.size(); i++)
{
String tempTitle = myBooks.get(i).getTitle();
ArrayList<String> tempAuthors = myBooks.get(i).getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
}
LibraryDriver.java:
import java.util.*;
import java.io.*;
public class LibraryDriver
{
public static void main(String[] theArgs)
{
Scanner inputFile = null;
PrintStream outputFile = null;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
ArrayList<Book> books2 = new ArrayList<Book>();
String[] filesInputs = new String[]{"LibraryIn1.txt", "LibraryIn2.txt"};
try
{
outputFile = new PrintStream(new File("LibraryOut.txt"));
for (String fileInput : filesInputs)
{
inputFile = new Scanner(new File(fileInput));
while (inputFile.hasNext())
{
String title = "";
String input = inputFile.nextLine();
//Read title
title = input;
input = inputFile.nextLine();
authors = getAuthors(input);
//Insert title & authors into a book
Book tempBook = new Book(title, authors);
//Add this book to the ArrayList<Book> of books
books.add(tempBook);
}
Library myLib = new Library(books);
outputFile.println(myLib);
inputFile.close();
myLib.sort();
outputFile.println(myLib);
}
}
catch (Exception e)
{
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
inputFile.close();
outputFile.close();
}
public static ArrayList<String> getAuthors(String theAuthors)
{
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++)
{
if (theAuthors.charAt(i) == '*')
{
if (lastAsteriskIndex > 0)
{
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
}
else
{
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0)
{
authorList.add(theAuthors);
}
return authorList;
}
}
So, I hobbled together a runnable example of your code as best as I could and using
The Hobbit
Tolkien, J.R.R
Acer Dumpling
Doofus, Robert
As input, I get
"The Hobbit" by Tolkien, J.R.R
"Acer Dumpling" by Doofus, Robert
The code:
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class LibraryDriver {
public static void main(String[] theArgs) {
// ArrayList<Book> books = new ArrayList<>(25);
// books.add(
// new Book("Bananas in pajamas",
// new ArrayList<>(Arrays.asList(new String[]{"B1", "B2"}))));
//
// Library lib = new Library(books);
// System.out.println(lib.toString());
Scanner inputFile = null;
PrintStream outputFile = null;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
ArrayList<Book> books2 = new ArrayList<Book>();
String[] filesInputs = new String[]{"LibraryIn1.txt"}; //, "LibraryIn2.txt"};
try {
outputFile = new PrintStream(new File("LibraryOut.txt"));
for (String fileInput : filesInputs) {
inputFile = new Scanner(new File(fileInput));
while (inputFile.hasNext()) {
String title = "";
String input = inputFile.nextLine();
//Read title
title = input;
input = inputFile.nextLine();
authors = getAuthors(input);
//Insert title & authors into a book
Book tempBook = new Book(title, authors);
//Add this book to the ArrayList<Book> of books
books.add(tempBook);
}
Library myLib = new Library(books);
outputFile.println(myLib);
inputFile.close();
// myLib.sort();
// outputFile.println(myLib);
}
} catch (Exception e) {
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
inputFile.close();
outputFile.close();
}
public static ArrayList<String> getAuthors(String theAuthors) {
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++) {
if (theAuthors.charAt(i) == '*') {
if (lastAsteriskIndex > 0) {
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
} else {
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0) {
authorList.add(theAuthors);
}
return authorList;
}
public static class Library {
private ArrayList<Book> myBooks;
public Library(final ArrayList<Book> theOther) {
if (theOther == null) {
throw new NullPointerException();
} else {
myBooks = new ArrayList<Book>();
for (int i = 0; i < theOther.size(); i++) {
myBooks.add(theOther.get(i));
}
}
}
public ArrayList<Book> findTitles(final String theTitle) {
ArrayList<Book> titleList = new ArrayList<Book>();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getTitle().equals(theTitle)) {
titleList.add(myBooks.get(i));
}
}
return titleList;
}
public String toString() {
String result = "";
for (int i = 0; i < myBooks.size(); i++) {
String tempTitle = myBooks.get(i).getTitle();
Book b = myBooks.get(i);
ArrayList<String> tempAuthors = b.getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
}
public static class Book implements Comparable<Book> {
private final String myTitle;
private final ArrayList<String> myAuthors;
public Book(final String theTitle, final ArrayList<String> theAuthors) {
if (theTitle == "" || theAuthors.isEmpty()
|| theTitle == null || theAuthors.get(0) == null) {
throw new IllegalArgumentException(
"The book must have a valid title AND author.");
} else {
myTitle = theTitle;
myAuthors = new ArrayList<String>();
for (int i = 0; i < theAuthors.size(); i++) {
myAuthors.add(theAuthors.get(i));
}
}
}
public String toString() {
String result = "\"" + myTitle + "\" by ";
for (int i = 0; i < myAuthors.size(); i++) {
result += (String) myAuthors.get(i);
}
return result;
}
#Override
public int compareTo(Book o) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public String getTitle() {
return myTitle;
}
public ArrayList<String> getAuthors(String theAuthors) {
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++) {
if (theAuthors.charAt(i) == '*') {
if (lastAsteriskIndex > 0) {
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
} else {
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0) {
authorList.add(theAuthors);
}
return authorList;
}
public ArrayList<String> getAuthors() {
return myAuthors;
}
}
}
Consider providing a runnable example which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses
I'm having trouble retrieving the Id from a JSONObject and passing it to a String to record the Id of that players particular puzzle but on the line String idString = obj.getString("Id");
"I get org.json.JSONException: No value for Id"
I'm getting this information by calling to the server in this class which checks the username and password of the player.
import android.os.AsyncTask;
import android.text.format.Time;
import android.util.Log;
public class GetTodaysPuzzle implements OnRetrieveHttpData {
public String GetTodaysPuzzle(String mUserName, String mPassword)
{
RetrieveHTTPData GetTodayspuzzle = new RetrieveHTTPData(this);
return GetTodayspuzzle.GetResponseData("urlString" + mUserName + "&password=" + mPassword);
}
#Override
public void onRetrieveTaskCompleted(String httpData) {
Log.i("Server Response", httpData);
}
class GetTodaysPuzzleTask extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
// Get response from server
String json = GetTodaysPuzzle(params[0], params[1]);
// Check if a puzzle was returned
if (json.contains("The request is invalid"))
{
return false;
}
try
{
// Calculate today's date in order to set wordsearch date
Time today = new Time();
today.setToNow();
String formattedDate = Dates.ConvertUStoUK(today.year + "-"
+ (today.month + 1) + "-" + today.monthDay);
// Create wordsearch
WordSearch wordSearch = WordSearch.CreateWordSearch(json,
formattedDate);
if (wordSearch == null)
{
return false;
}
// Save wordsearch to collection
WordSearchDatabase.Add(wordSearch);
// WordSearchDatabase.Save();
return true;
}
catch (Exception e)
{
Log.e("GetTodaysPuzzleTask", e.getMessage());
return false;
}
}
}
}
And then stores all the information into JSONArrays in the Wordsearch class.
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class WordSearch {
public String Id;
public String Date;
public List<Word> Words;
public Letter[] Letters;
public final int NUM_OF_ROWS;
public final int NUM_OF_COLS;
public int Score = -1;
private boolean containsSolution = false;
public boolean canBeSubmitted = true;
private boolean complete = false;
private boolean submitted = false;
public static WordSearch CreateWordSearch(String json, String date)
{
List<Word> listOfWords = new ArrayList<Word>();
List<String> listOfRows = new ArrayList<String>();
try
{
// Create a JSON Object from JSON string
JSONObject obj = new JSONObject(json);
// Get Id
String idString = obj.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = obj.getJSONArray("Words");
JSONArray puzzleArray = obj.getJSONArray("Grid");
// Parse Words array
for (int i = 0; i < wordsArray.length(); i++)
{
String name = wordsArray.getString(i);
Word word = new Word(name);
listOfWords.add(word);
}
// Parse Puzzle
for (int k = 0; k < puzzleArray.length(); k++)
{
String puzzle = puzzleArray.getString(k);
listOfRows.add(puzzle);
}
// Create WordSearch
return new WordSearch(idString, date, listOfWords, listOfRows,
false);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
This is the first time I have used API servers and JSONObject's in Android so any help would be much appreciated. Thank you.
You are getting this error because your response JSON doesn't have "Id" as a key, It only has "Puzzle" as you can see:
{
"Puzzle": {
"Id": "8fb25209-863a-410b-a440-b5b57a903ee1",
"Words": ["CHATEAUX", ...],
"Grid": ["TLIOFSHTRC", ...]
}
}
You need to first get the "Puzzle" object first and then you can get the "Id" from that object.
JSONObject obj = new JSONObject(json);
JSONObject puzzle = obj.getJSONObject("Puzzle");
String idString = puzzle.getString("Id");
....
Id is in the puzzle element so it should be
JSONObject obj = new JSONObject(json);
//get puzzle object
JSONObject puzzle = obj.getJSONObject("Puzzle");
// Get Id
String idString = puzzle.getString("Id");
// GetWords & Puzzle as JSON Arrays
JSONArray wordsArray = puzzle.getJSONArray("Words");
JSONArray puzzleArray = puzzle.getJSONArray("Grid");