0

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?

4
  • 1
    include the code u used to initialize the cur object as well.. Commented Apr 11, 2014 at 6:51
  • 1
    according to jsonlint.com this is not valid json. Commented Apr 11, 2014 at 6:51
  • 1
    I guess, the empty objects ({ }) will cause a problem when you try to access the Otype field. Did the code throw an exception? Commented Apr 11, 2014 at 6:54
  • Hi by mistake I write wrong json format but now I changed json format Commented Apr 11, 2014 at 7:01

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I am wondering how you get an iterator out of your given JSON String?
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 .
0

use toString() like this

System.out.print(jObject.toString());

2 Comments

If I print above then it shows me all json formatted string, I just wanted to access values of given key.
try this, System.out.print("{ \"Otype\" : \""+jObject.getString("Otype")+"\"}");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.