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);
Related
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.
I have this array list in java
[ {"pname":"7", "qty":"222"},
{"pname":"8", "qty":"5"},
{"pname":"9", "qty":"60"} ]
I can access the first index which is object, how can I access the first element inside the first object which is "pname" key in java syntax. Please give me sample codes. Thanks.
I tried:
mylist.get(0)
but it only gives me the first object. I don't know how to access the first index inside the object.
here is my whole code from getting the data to parse it into json array and convert to array list
String data = request.getParameter("data");
JSONArray jsonArray = new JSONArray(data);
ArrayList<String> mylist = new ArrayList<String>();
JSONArray this_is_jsonArray = (JSONArray)jsonArray;
if (jsonArray == null) {
System.out.println("json is empty");
}
else
{
int length = this_is_jsonArray.length();
for (int i=0;i<length;i++){
mylist.add(this_is_jsonArray.get(i).toString());
}
}
output.append(mylist);
Basically I'm trying to do a function similar output to this mylist[0].pname in javascript. the expected output all in all is to save those pnames and qtys to a variable for me to able to send each value to the database
In order to write a proper answer you need to be very clear about the input and output you have and you expect.
I don't understand why you want to create a parallel data structure instead of using the parsed JSON but from what I read in comments I think that you need to change the structure of your ArrayList content in order to obtain the result you want to achieve.
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"9\", \"qty\":\"60\"} ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.put("pname", jsonObject.getString("pname"));
item.put("qty", jsonObject.getString("qty"));
mylist.add(item);
}
}
System.out.println(mylist);
First thing to consider is JSON object is not ordered.The first object can be pname or qty, in successive request. To access the fields, give field name as an associative array.
JSONArray jsonArray = new JSONArray(data);
ArrayList<String> mylist = new ArrayList<String>();
JSONArray this_is_jsonArray = (JSONArray)jsonArray;
if (jsonArray == null) {
System.out.println("json is empty");
}
else
{
int length = this_is_jsonArray.length();
for (int i=0;i<length;i++){
// Just this line is modified
mylist.add(this_is_jsonArray.getJSONObject(i).getString("pname").toString());
}
}
I have some JSON that is returned as follows:
[{"on_arrival_inst":"Ok","order_inst":"Ok","finished_inst":"Ok"},{"on_arrival_inst":"Arrive","order_inst":"Order","finished_inst":"Finished"}]
I am trying to split these into two arrays and get the strings out as follows:
jsonResultsObject = new JSONObject(result);
jsonArray = jsonResultsObject.getJSONArray("");
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
However the code never goes into the loop, as the array is not getting populated from the JSONObject?
your result is JSONArray not JSONObject. That's why you must convert it to array not to object.
use
jsonResultsArray = new JSONArray(result);
instead of
jsonResultsObject = new JSONObject(result);
and the full code will be
jsonResultsArray = new JSONArray(result);
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonResultsArray.length()){
JSONObject JO = jsonResultsArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
#BigJimmyJones
The fact of that the code does not enter the loop is just because your JSONArray does not have a key named "" but it contains JSONObjects instead. Objects and arrays in JSON have different annotations. See: JSON Reference Website
So your code should be :
jsonResultsObject = new JSONObject(result);
String onArrive, onReady, onFinished;
for (int i=0;i<jsonArray.length();i++){
JSONObject JO = jsonArray.getJSONObject(i);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
}
And also ensure that your code is inside a try - catch block to catch JSONException
I'm parsing a jsonData and getting the video_url from it. What my requirements is to add the video_url inside the ArrayList. I've tried everything and getting the result as this in my logCat :
E/VIDEO URL: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FJIMyHoviVideo.mp4?alt=media&token=c103543e-31f0-4682-9b44-09d679c76699]
E/VIDEO URL: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FBMMyHoviVideo.mp4?alt=media&token=9bcf98a1-dad1-4f63-864f-7559ef1d49c1]
Now here you can clearly see that the video_url is coming in this format what I want a single ArrayList containing both the url.
This is the code I've done to print the desired result but it is not coming fine :
private void jsonParsingVideoData(String projectVideos, String projectId) throws JSONException{
JSONArray jsonArray = new JSONArray(projectVideos);
ArrayList<String> video_url = null;
for(int i=0; i< jsonArray.length() ; i++){
JSONObject jObject = jsonArray.getJSONObject(i);
video_url = new ArrayList<>(Arrays.asList(jObject.getString("video_url")));
Log.e("VIDEO URL", video_url.toString());
}
}
I've tried in this way also but it failed, only one output is there if I'm doing in this way out of the loop.
for( String string : video_url){
ArrayList<String> string1 = new ArrayList<>();
string.add(string);
Log.e("LOGS", string1.toString());
}
for the above code the output is coming only one and in this format :
E/LOGS: [https://firebasestorage.googleapis.com/v0/b/myhovi-android.appspot.com/o/MySavedVideo%2FBMMyHoviVideo.mp4?alt=media&token=9bcf98a1-dad1-4f63-864f-7559ef1d49c1]
Please help me with this, I've tried a lot. Thanks.
You are creating a new ArrayList every loop iteration. You should use add instead!
private void jsonParsingVideoData(String projectVideos, String projectId) throws JSONException{
JSONArray jsonArray = new JSONArray(projectVideos);
ArrayList<String> video_urls = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jObject = jsonArray.getJSONObject(i);
video_urls.add(jObject.getString("video_url"));
}
}
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);
}