I had following json format :
[
{ "Otype" : "win"},
{ "Otype" : "win"},
{ },
{ },
{ "Otype" : " win 7"},
{ "Otype" : " Linux"}
]
for accessing Otype I write java code as below:
while(cur.hasNext() && !isStopped()) {
String json = cur.next().toString();
JSONObject jObject = new JSONObject(json);
System.out.print(jObject.getString("Otype"));
}//end of while
So above print statement print only following results:
win
win
but not print:
{ "Otype" : " win 7"}
{ "Otype" : " Linux"}
I think it may be first white space in value field that's why it not print above two key so I changed in print statement as below:
System.out.print(jObject.getString("Otype").trim());
but still not work :( .
How I can access all above json value using java code?
asked Apr 11, 2014 at 6:48
Neo-coder
7,8565 gold badges36 silver badges54 bronze badges
2 Answers 2
I found my solution. I changed my code as below:
while(cur.hasNext() && !isStopped()) {
String json = cur.next().toString();
JSONObject jObject = new JSONObject(json);
if(jObject.has("Otype")){
System.out.print(jObject.getString("Otype"));
}//end of if
}//end of while
Michal Kordas
11k10 gold badges65 silver badges118 bronze badges
answered Apr 11, 2014 at 7:07
Neo-coder
7,8565 gold badges36 silver badges54 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
chris polzer
I am wondering how you get an iterator out of your given JSON String?
Neo-coder
Hi I read mongo data using java code so before while I was write my query and set cur as DBCursor so in while it iterates all my json data .
use toString() like this
System.out.print(jObject.toString());
answered Apr 11, 2014 at 6:53
Balayesu Chilakalapudi
1,4023 gold badges20 silver badges43 bronze badges
2 Comments
Neo-coder
If I print above then it shows me all json formatted string, I just wanted to access values of given key.
Balayesu Chilakalapudi
try this, System.out.print("{ \"Otype\" : \""+jObject.getString("Otype")+"\"}");
lang-java
{ }) will cause a problem when you try to access theOtypefield. Did the code throw an exception?