0

Below is the json file i am trying to parse.I want to print all key and corresponding values.

{
 "A":{
   "name":"Ram",
   "gender":"male",
   "designation":"engineer"
 },
 "B":{
  "name":"Shyam",
  "gender":"male",
  "designation":"student"
 },
 "C":{
  "name":"Mohan",
  "gender":"male",
  "designation":"manager"
 }
} 

I have tried the following code:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;

public class FetchJsonNested {
    public static void main(String args[]) throws FileNotFoundException {
        try {
            JSONParser jp=new JSONParser();
            Object obj=jp.parse(new FileReader("C:\\Users\\DELL\\Documents\\NetBeansProjects\\WaterNetwork\\web\\kusharray.json"));
            JSONObject job=(JSONObject)obj;
            Iterator < ? > keys = job.keys();

            while (keys.hasNext()) {
                String key = (String) keys.next();
                System.out.println(key);
                if (job.get(key) instanceof JSONObject) {
                    System.out.println(job.get(key));
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

I have read stuffs from many site but no one is working like the way i want.I want to print all keys and corresponding values.

7
  • please add an output example Commented Jun 22, 2017 at 7:34
  • I am getting an exception as follow: Commented Jun 22, 2017 at 7:36
  • java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.JSONObject Commented Jun 22, 2017 at 7:36
  • I just want to print the key(For example "A") and after that using the nested key to get corresponding value.something like this name="Ram" Commented Jun 22, 2017 at 7:42
  • You're supposed to ask questions, "suggest me a working code" is asking someone to code it for you. Commented Jun 22, 2017 at 7:51

2 Answers 2

1

Using org.json as you did in your example :

String jsonStr = "{\"A\":{\"name\":\"Ram\",\"gender\":\"male\",\"designation\":\"engineer\"},\"B\":{\"name\":\"Shyam\",\"gender\":\"male\",\"designation\":\"student\"},\"C\":{\"name\":\"Mohan\",\"gender\":\"male\",\"designation\":\"manager\"}}";
JSONObject json = new JSONObject(jsonStr);

for (Object key : json.keySet().toArray()){
    JSONObject data = json.getJSONObject(key.toString());
    System.out.println("json :" + data.toString());
    System.out.println("name :" +data.getString("name"));
    System.out.println("gender :" +data.getString("gender"));
    System.out.println("designation :" +data.getString("designation"));
}

Now you can replace my first line "String jsonStr = ..." with your file reader.

Sign up to request clarification or add additional context in comments.

Comments

0

below follow not the awesome and most elegant solution but this can lead you to what you need.

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Main {

    public static void main(String[] args) throws Exception {
        String jsonString = loadJSONFile();

        JsonElement jsonElement = new JsonParser().parse(jsonString);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        print(jsonObject);
    }

    private static String loadJSONFile() throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader("path/to/the/json/file.ext"));
        StringBuilder stringBuilder = new StringBuilder();

        while (scanner.hasNext()) {
            stringBuilder.append(scanner.next());
        }

        scanner.close();

        return stringBuilder.toString();
    }

    private static void print(JsonObject jsonObject) {
        Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();

        for (Map.Entry<String, JsonElement> entry : entries) {
            System.out.println(entry.getKey() + ": " + entry.getValue());

            try {
                JsonElement jsonElement = new JsonParser().parse(String.valueOf(entry.getValue()));
                JsonObject innerJsonObject = jsonElement.getAsJsonObject();

                print(innerJsonObject);
            } catch (Exception e) {
                // is not a JSON
            }
        }
    }
}

Output example:

A: {"name":"Ram","gender":"male","designation":"engineer"}
name: "Ram"
gender: "male"
designation: "engineer"
B: {"name":"Shyam","gender":"male","designation":"student"}
name: "Shyam"
gender: "male"
designation: "student"
C: {"name":"Mohan","gender":"male","designation":"manager"}
name: "Mohan"
gender: "male"
designation: "manager"

2 Comments

thanks a lot.But sir the json file is dynamic.so how can I convert json file to string all the time it get updated.
thnxx a lot sir.

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.