I m trying get data from json file and saved as objects and then put into different arrylist, i m stuck on the point where i coundnt get "A320" into a obejcts, "type_ratings": [
"A320"
]
List<Crew> Allcrews = new ArrayList<>();
List<Pilot> pilotsList = new ArrayList<>();
List<CabinCrew> Cabincrews = new ArrayList<>();`
public void loadCrewData(Path p) throws DataLoadingException{
try {
BufferedReader reader = Files.newBufferedReader(p);
String jsonStr = "";
String line = "";
while ((line=reader.readLine()) !=null)
{
jsonStr =jsonStr+line;
}
System.out.println ("Pilots Informations: ");
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray pilots = jsonObj.getJSONArray("pilots");
for(int j =0; j<pilots.length(); j++) {
JSONObject pilot = pilots.getJSONObject(j);
Pilot pil = new Pilot();
pil.setForename(pilot.getString("forename"));
pil.setHomeBase(pilot.getString("home_airport"));
pil.setSurname(pilot.getString("surname"));
pil.setRank(Rank.CAPTAIN);
pil.setRank(Rank.FIRST_OFFICER);
pil.setQualifiedFor(pilot.getString("type_ratings"));;
pilotsList.add(pil);
Allcrews.add(pil);
System.out.println( "Forename: " +pilot.getString("forename"));
System.out.println( "Surname: " +pilot.getString("surname"));
System.out.println( "Rank: " +pilot.getString("rank"));
System.out.println("Home_Airport: " + pilot.getString("home_airport"));
System.out.println("type_ratings: " + pilot.getJSONArray("type_ratings"));
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}[![JSONFile][1]][1]
The "type_ratings" key will return a JSONArray, not a String. This is because of the square brackets that surround the string, making it an array with 1 element. You could either change the JSON structure and remove the square brackets in order to only make it a String, or you could simply do pil.setQualifiedFor(pilot.getJSONArray("type_ratings")[0]);, which will get the array, and return the first element, the string. Keep in mind that you should only do this if you know that type_ratings will always contain an array with 1 string.
Related
I have json like this
{"First":["Already exists"],"Second":["Already exists"]}
Currently I am doing like
JSONObject jObject = new JSONObject(myJson);
String first = jObject.getString("First")
But I am getting result like this
first = ["Already exists"]
But I want string without square brackets or ""
Try using JSONArray :
JSONArray jArray = new JSONObject(myJson).getJSONArray("First");
String first = jArray.getString(0);
Your json message with key 'first' is Array. So use should treat as Array.
String string = "{'First':['Already exists'],'Second':['Already exists']}";
JSONObject jObject;
try
{
jObject = new JSONObject(string);
Object myJson = jObject.get("First");
if(myJson instanceof JSONArray)
{
JSONArray jArray = jObject.getJSONArray("First");
for (int i = 0; i < jArray.length(); i++)
{
System.out.println("val : "+jArray.getString(i));
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
Thanks to #m.qadhavi i was able to figure out how it works
//This was my temporary solution
//get no. of garage
properties.setPropertyFeaturesGarage(jsonObject
.getJSONObject("extras")
.getString("property_garages")
.replaceAll("[\"]", "")
.replace('[',' ')
.replace(']',' '));
But after going through #m.qadhavi explanation i corrected my code
//get land size
properties.setPropertyFeaturesLandSize(jsonObject
.getJSONObject("extras")
.getJSONArray("property_size")
.getString(0));
Happy Coding
Try to get Substring like e.g.
String first = jObject.getString("First")
String subFirst = first.substring(2,first.length()-2);
I have got 3000 symbols present in java array .
I am using ROME API to fetch the rss feeds ,
then i am trying to check if the title contains anything part of array then only i must display the title
This is my program
String[] myFirstStringArray = new String[] {"ONE","TWO"}; // 3000 symbols
try {
String url = "http://www.rssmix.com/u/8159030/rss.xml";
URL feedUrl = new URL(url);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
for (SyndEntry entry : (List<SyndEntry>) feed.getEntries()) {
JSONObject jsonobj_latestnews = new JSONObject();
String title = entry.getTitle();
jsonobj_latestnews.put("title", title)
latestnews.put(jsonobj_latestnews);
}
} catch (Exception e) {
e.printStackTrace();
}
Could you please tell me how to check
assuming that the title is likely to be much less than the size of array.
String [] titleWords = title.split(" ");
ArrayList<String> wordList = Arrays.asList(myFirstStringArray);
for (String word : titleWords)
{
if(wordList.contains(word))
{
/*do something here. you can get the index of the word by
wordList.indexOf(word); this index will the same as the index in myFirstStringArray*/
break;
}
}
this should do it
I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}
I want to parse a json object in java.The json file is {"l1":"1","l2":"0","f1":"0","connected":"0","all":"0"}
i am trying to write a java program to print above json as
l1=1
l2=0
f1=0
connected=0
all=0
The number of entries in the json file can be increased, so i have to loop through the json and print all data. This is what i've done so far.
public class main {
public static void main(String[] args){
try{
URL url = new URL("http://localhost/switch.json");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject root = new JSONObject(tokener);
JSONArray jsonArray = root.names();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
System.out.println(jsonArray.get(i).toString());
}
}
}catch (Exception e) {
e.printStackTrace();
System.out.println("Error Occured");
}
}
}
the above program can only print the first item of each array. But i am trying get the result i mentioned in the beginning. Can anybody help ??
It is simple JSON object, not an array. You need to iterate through keys and print data:
JSONObject root = new JSONObject(tokener);
Iterator<?> keys = root.keys();
while(keys.hasNext()){
String key = (String)keys.next();
System.out.println(key + "=" + root.getString(key));
}
Please note that above solution prints keys in a random order, due to usage of HashMap internally. Please refer to this SO question describing this behavior.
Your JSON file does not contain an array - it contains an object.
JSON arrays are enclosed in [] brackets; JSON objects are enclosed in {} brackets.
[1, 2, 3] // array
{ one:1, two:2, three:3 } // object
Your code currently extracts the names from this object, then prints those out:
JSONObject root = new JSONObject(tokener);
JSONArray jsonArray = root.names();
Instead of looping over just the names, you need to use the names (keys) to extract each value from the object:
JSONObject root = new JSONObject(tokener);
for (Iterator<?> keys= root.keys(); keys.hasNext();){
System.out.println(key + "=" + root.get(keys.next()));
}
Note that the entries will not print out in any particular order, because JSON objects are not ordered:
An object is an unordered set of name/value pairs -- http://json.org/
See also the documentation for the JSONObject class.
I have a JSON file (.json) in Amazon S3. I need to read it and create a new field called Hash_index for each JsonObject. The file is very big, so I am using a GSON library to avoid my OutOfMemoryError in reading the file. Below is my code. Please note that I am using GSON
//Create the Hashed JSON
public void createHash() throws IOException
{
System.out.println("Hash Creation Started");
strBuffer = new StringBuffer("");
try
{
//List all the Buckets
List<Bucket>buckets = s3.listBuckets();
for(int i=0;i<buckets.size();i++)
{
System.out.println("- "+(buckets.get(i)).getName());
}
//Downloading the Object
System.out.println("Downloading Object");
S3Object s3Object = s3.getObject(new GetObjectRequest(inputBucket, inputFile));
System.out.println("Content-Type: " + s3Object.getObjectMetadata().getContentType());
//Read the JSON File
/*BufferedReader reader = new BufferedReader(new InputStreamReader(s3Object.getObjectContent()));
while (true) {
String line = reader.readLine();
if (line == null) break;
// System.out.println(" " + line);
strBuffer.append(line);
}*/
// JSONTokener jTokener = new JSONTokener(new BufferedReader(new InputStreamReader(s3Object.getObjectContent())));
// jsonArray = new JSONArray(jTokener);
JsonReader reader = new JsonReader( new BufferedReader(new InputStreamReader(s3Object.getObjectContent())) );
reader.beginArray();
int gsonVal = 0;
while (reader.hasNext()) {
JsonParser _parser = new JsonParser();
JsonElement jsonElement = _parser.parse(reader);
JsonObject jsonObject1 = jsonElement.getAsJsonObject();
//Do something
StringBuffer hashIndex = new StringBuffer("");
//Add Title and Body Together to the list
String titleAndBodyContainer = jsonObject1.get("title")+" "+jsonObject1.get("body");
//Remove full stops and commas
titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " ");
titleAndBodyContainer = titleAndBodyContainer.replaceAll(",", " ");
titleAndBodyContainer = titleAndBodyContainer.toLowerCase();
//Create a word list without duplicated words
StringBuilder result = new StringBuilder();
HashSet<String> set = new HashSet<String>();
for(String s : titleAndBodyContainer.split(" ")) {
if (!set.contains(s)) {
result.append(s);
result.append(" ");
set.add(s);
}
}
//System.out.println(result.toString());
//Re-Arranging everything into Alphabetic Order
String testString = "acarpous barnyard gleet diabolize acarus creosol eaten gleet absorbance";
//String testHash = "057 1$k 983 5*1 058 52j 6!v 983 03z";
String[]finalWordHolder = (result.toString()).split(" ");
Arrays.sort(finalWordHolder);
//Navigate through text and create the Hash
for(int arrayCount=0;arrayCount<finalWordHolder.length;arrayCount++)
{
if(wordMap.containsKey(finalWordHolder[arrayCount]))
{
hashIndex.append((String)wordMap.get(finalWordHolder[arrayCount]));
}
}
//System.out.println(hashIndex.toString().trim());
jsonObject1.addProperty("hash_index", hashIndex.toString().trim());
jsonObject1.addProperty("primary_key", gsonVal);
jsonObjectHolder.add(jsonObject1); //Add the JSON Object to the JSON collection
jsonHashHolder.add(hashIndex.toString().trim());
System.out.println("Primary Key: "+jsonObject1.get("primary_key"));
//System.out.println(Arrays.toString(finalWordHolder));
//System.out.println("- "+hashIndex.toString());
//break;
gsonVal++;
}
System.out.println("Hash Creation Completed");
}
catch(Exception e)
{
e.printStackTrace();
}
}
When this code is executed, I got the following error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2894)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:117)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:407)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at HashCreator.createHash(HashCreator.java:252)
at HashCreator.<init>(HashCreator.java:66)
at Main.main(Main.java:9)
[root#ip-172-31-45-123 JarFiles]#
Line number 252 is - result.append(s);. It is Inside the HashSet loop.
Previously, it generated OutOfMemoryError in line number 254. Line number 254 is - set.add(s); it is also inside the HashSet array.
My Json files are really really big. Gigabytes and Terabytes. I have no idea about how to avoid the above issue.
Use a streaming JSON library like Jackson.
Read in a some JSON, add the hash, and write them out.
Then read in some more, process them, and write them out.
Keep going until you have processed all the objects.
http://wiki.fasterxml.com/JacksonInFiveMinutes#Streaming_API_Example
(See also this StackOverflow post: Is there a streaming API for JSON?)