1

I'm trying to parse recursively unknown json input structure in java like the format below and trying to rewrite the same structure in another json.

Meanwhile I need to validate each & every json key/values while parsing.

{"Verbs":[{
    "aaaa":"30d", "type":"ed", "rel":1.0, "id":"80", "spoken":"en", "ct":"on", "sps":null
},{
    "aaaa":"31", "type":"cc", "rel":3.0, "id":"10", "spoken":"en", "ct":"off", "sps":null
},{
    "aaaa":"81", "type":"nn", "rel":3.0, "id":"60", "spoken":"en", "ct":"on", "sps":null
}]}

Please advice which json parser I can use for reading and writing unknown json content.

erdarun
  • 441
  • 1
  • 8
  • 14
  • 2
    Any. Its json; they parse it. – Brian Roach Mar 01 '14 at 08:07
  • How to parse each json element and reassemble it as same as input – erdarun Mar 01 '14 at 08:09
  • What do you want to do with parsed data? – Leos Literak Mar 01 '14 at 08:37
  • I want to validate each & every json token key/value for special chars. Then I will replace the values and reframe json again back to old structure – erdarun Mar 01 '14 at 09:08
  • I submitted sample that you can reuse as template. Just set value instead of printing. And once you are finished, just print the tree with method on parent object. Nevertheless I wonder if it is neccessary, JSON library shall escape neccessary characters for you. – Leos Literak Mar 01 '14 at 09:27
  • Use a JSON parser to parse it, update what you want to in the resulting structures, and then use the companion JSON serializer to produce a new JSON string. You can use any of a dozen different parser/serializer kits, and probably the simpler the better. – Hot Licks Mar 01 '14 at 19:21
  • 1
    (Don't use Jackson, or any other "we'll build your POJOs for you" tool, unless the structure is fairly regular and repeatable. Unless you really understand them they cause more confusion than they're worth.) – Hot Licks Mar 01 '14 at 19:26

2 Answers2

4

This way you can recursively parse JSON object:

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

public class JsonQuestion {

    public static void main(String[] args) {
        String input =  "{\"Verbs\":[{\n" +
                "    \"aaaa\":\"30d\", \"type\":\"ed\", \"rel\":1.0, \"id\":\"80\", \"spoken\":\"en\", \"ct\":\"on\", \"sps\":null\n" +
                "},{\n" +
                "    \"aaaa\":\"31\", \"type\":\"cc\", \"rel\":3.0, \"id\":\"10\", \"spoken\":\"en\", \"ct\":\"off\", \"sps\":null\n" +
                "},{\n" +
                "    \"aaaa\":\"81\", \"type\":\"nn\", \"rel\":3.0, \"id\":\"60\", \"spoken\":\"en\", \"ct\":\"on\", \"sps\":null\n" +
                "}]}";

        JsonObject jsonObject = JsonObject.readFrom(input);
        handleObject(jsonObject);
    }

    private static void handleValue(JsonObject.Member member, JsonValue value) {
        if (value.isArray()) {
            if (member != null) {
                System.out.print("name = " + member.getName());
            }
            System.out.println("array value ");
            recurseArray(value.asArray());
        } else if (value.isBoolean()) {
            if (member != null) {
                System.out.print("name = " + member.getName());
            }
            System.out.println(", boolean value = " + value.asBoolean());
        } else if (value.isNull()) {
            if (member != null) {
                System.out.print("name = " + member.getName());
            }
            System.out.println(", null value");
        } else if (value.isNumber()) {
            if (member != null) {
                System.out.print("name = " + member.getName());
            }
            System.out.println(", number value = " + value.asDouble());
        } else if (value.isObject()) {
            if (member != null) {
                System.out.print("name = " + member.getName());
            }
            System.out.println(", object value ");
            handleObject(value.asObject());
        } else if (value.isString()) {
            if (member != null) {
                System.out.print("name = " + member.getName());
            }
            System.out.println(", string value = " + value.asString());
        }
    }

    private static void handleObject(JsonObject object) {
        for (JsonObject.Member next : object) {
            JsonValue value = next.getValue();
            handleValue(next, value);
        }
    }

    private static void recurseArray(JsonArray array) {
        for (JsonValue value : array) {
            handleValue(null, value);
        }
    }
}
Leos Literak
  • 8,805
  • 19
  • 81
  • 156
2

Using gson library https://sites.google.com/site/gson/gson-user-guide

public void parseJson() {
     String jsonStr = "";//input json String.
     JsonParser parser = new JsonParser();
     JsonElement jsonElement = parser.parse(jsonStr);
     processJsonElement(jsonElement);
}


private void processJsonElement(JsonElement e) {
    if (e.isJsonArray()) {
        processJsonArray(e.getAsJsonArray());
    } else if (e.isJsonNull()) {
        processJsonNull(e.getAsJsonNull());
    } else if (e.isJsonObject()) {
        processJsonObject(e.getAsJsonObject());
    } else if (e.isJsonPrimitive()) {
        processJsonPrimitive(e.getAsJsonPrimitive());
    }
}

private void processJsonArray(JsonArray a) {
    for (JsonElement e : a) {
        processJsonElement(e);
    }
}

private void processJsonNull(JsonNull n) {
    System.out.println("null || : " + n);
}

private void processJsonObject(JsonObject o) {
    Set<Map.Entry<String, JsonElement>> members= o.entrySet();
    for (Map.Entry<String, JsonElement> e : members) {
        System.out.println("Processing object member: " + e.getKey());
        processJsonElement(e.getValue());
    }
}

private void processJsonPrimitive(JsonPrimitive p) {
    System.out.println("Primitive || :" + p);
}

Or Jackson

public void processJson() {
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        JsonNode node = objectMapper.readTree(jsonStr);
        System.out.println(node);
        processNode(node);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

private void processNode(JsonNode n) {
    if (n.isContainerNode()) {
        processJsonContainer(n.iterator());
    } else if (n.isNull()) {
        System.out.println("Null || :" + n);
    } else if (n.isNumber()) {
        System.out.println("Number || :" + n.asDouble());
    } else if (n.isBoolean()) {
        System.out.println("Boolean || :" + n.asBoolean());
    } else if (n.isTextual()) {
        System.out.println("Text || :" + n.asText());
    }
}

private void processJsonContainer(Iterator<JsonNode> iterator) {
   while (iterator.hasNext()) {
       processNode(iterator.next());
   }
}
helvete
  • 2,455
  • 13
  • 33
  • 37
Yan Khonski
  • 12,225
  • 15
  • 76
  • 114