-1

I have a JSONObject consisting of a simple json document(doesn't consists nested objects or JSONArray). I want to print that data.

import org.json.JSONObject;
import java.util.Scanner;
public class Test2{
  public static void main(String[] args) {
    Scanner scan=new Scanner(System.in);
    String s=scan.nextLine();
    JSONObject j=new JSONObject(s);
    // What code should I write here
  }
}

Let us say if the input is {fname:"Stack", lname:"Overflow"} then the output should be:-

fname => Stack
lname => Overflow

If the input is {country:"India", city:"Delhi"}then the output should be:-

country => India
city => Delhi

Can you please help me how I can do it.

Honey Yadav
  • 176
  • 1
  • 12

1 Answers1

1

From the documentation you can iterate over the keys, and take the values :

  1. Using Streams :

    j.keySet().stream().map(k -> k +"=>"+ j.get(k)).forEach(System.out::println);
    
  2. Using classic for each loop

    for(String key : j.keySet()){
        String val = j.getString(key);
        System.out.println(key +"=>"+ val);
    }
    

Also you JSON is not valid, it should be {"fname":"Stack", "lname":"Overflow"}

azro
  • 53,056
  • 7
  • 34
  • 70
  • you should not spend this much time answering a question that has been asked and answered many times before already. Just throw a close vote at it and move on – Tim Jul 18 '18 at 11:45
  • @TimCastelijns I usually, and always do that when possible, but duplicates came after my answer, and I did not know them, also I did not use the same way but less old wy as for each and stream and not basic arry iteration like in the link – azro Jul 18 '18 at 11:48
  • *duplicates came after my answer* - it takes 10 seconds to search for them. You can also do this yourself before answering – Tim Jul 18 '18 at 11:52