简体   繁体   中英

How to Read Json File Without Giving Element Names in Java

I want to read json file as follow;

{
  "M": {
  "row": [
  {
  "col1": "c00"
  },
  {
  "col1": "c10",
  "col2": "c11"
  },
  {
  "col1": "c20",
  "col2": "c21",
  "col3": "c22"
  }
  ]
  }
}

Next to reading, I want to print "c00","c10","c11","c20","c21","c22" but without giving element as "col1","col2","col3"... Thanks for helping.

Use any JSON parsing library such as GSON or Jackson and convert it into Java Object.

Sample code using GSON library

 Type type = new TypeToken<Map<String, Object>>() {}.getType();
 Map<String, Object> data = new Gson().fromJson(jsonString, type);
 System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
 // get the desired value from map

 Map<String,ArrayList<Map<String,String>>> mMap=(Map<String,ArrayList<Map<String,String>>>)data.get("M");
 ArrayList<Map<String,String>> rowArray=mMap.get("row");
 for(Map<String,String> colMap:rowArray){
     for(String value:colMap.values()){
         System.out.println(value);
     }
 }

You can convert JSON string into Java POJO class as well that is replica of the JSON string

class MDetails {
    private MDetail M;
    // getter & setter
}

class MDetail {
    private ArrayList<Map<String, String>> row;
    // getter & setter
}

...
MDetails data = new Gson().fromJson(jsonString, MDetails.class);
for (Map<String, String> colMap : data.getM().getRow()) {
    for (String value : colMap.values()) {
        System.out.println(value);
    }
}

You can use different field name using @SerializedName annotation.

 class MDetails {
    @SerializedName("M")
    private MDetail mDetail;
    // getter & setter         
 }

As per comments, the keys are dynamic so iterate the map containing another map in it and print all the values whose key starts with col

sample code: (call below method that recursively iterate all keys and values)

public static void printColValues(Object data) {
    if (data instanceof Map) {
        for (Map.Entry<String, Object> entry : ((Map<String, Object>) data).entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("col")) {
                System.out.println(entry.getValue());
            } else {
                printColValues(entry.getValue());
            }
        }
    } else if (data instanceof List) {
        for (Object obj : (List) data) {
            printColValues(obj);
        }
    }
}

output:

c00
c10
c11
c20
c21
c22

OR if nothing works then try with regex pattern but keep it as last resort

("col\d+":)("[^"]*")

Here is online demo

Or try with Reluctant Qualifier

("col\d+":)(".*?")

Here is demo

sample code:

String jsonString = "{\"M\":{\"row\":[{\"col1\":\"c00\"},{\"col1\":\"c10\",\"col2\":\"c11\"},{\"col1\":\"c20\",\"col2\":\"c21\",\"col3\":\"c22\"}]}}";
Pattern p = Pattern.compile("(\"col\\d+\":)(\"[^\"]*\")");
Matcher m = p.matcher(jsonString);
while (m.find()) {
    System.out.println(m.group(2));
}

output:

"c00"
"c10"
"c11"
"c20"
"c21"
"c22"

Code updated to print all values regardless of keys

public static void printColValues(Object data) {
    if (data instanceof Map) {
        for (Map.Entry<String, Object> entry : ((Map<String, Object>) data).entrySet()) {
            Object value=entry.getValue();
            if (value instanceof String) {
                System.out.println(value);
            } else {
                printColValues(value);
            }
        }
    } else if (data instanceof List) {
        for (Object obj : (List) data) {
            printColValues(obj);
        }
    }
}

You can use org.json library for this. It is here . General idea:

JSONObject obj = new JSONObject(sourceString);
for(String key : obj.keys()){
    String value = obj.getString(key);
    // Process value here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM