Is it possible to work with a previously unknown JSON structure?

I know this way:

Json json = new Json(); MyClass myJson = json.fromJson(MyClass.class, str); 

but for him it is necessary to know the JSON structure and create a class hierarchy, and what if the json file structure is not known in advance, can it be processed?

for example in JS, you can convert any json into an object and process its fields in a loop

UPDATE

talk about the complex structure:

 { "id": 1, "name": "my name", "options": { "desc":"text", "flags": [1,3,5], "object" : { "field1":"value", "field2":"value2", "field3":"value2" } } } 
  • In the case of jackson, you can simply convert to Object, and that will be either a List or Map - etki
  • one
    Most likely, your decision ideally would not be a class, but something like nested nodes. Generating a class in realtime seems to be real, but working with this class will be an order of magnitude more difficult than parsing string data from json ... In general, in the Json library of Java, you can refer to the fields as strings, and this will be An order of magnitude easier than reflexing a class changing its structure on the move ... - test123
  • @ test123, updated the question. Is it possible to handle complex json without knowing in advance its structure? - ravend
  • @ravend Ie don't you know its structure at all ?? And why is he needed then? :) I come to the entrance, I do not know what, but from there I want something. Please describe what you want to do with this json? Run through it? - learp

1 answer 1

Gson has the following method:

 JsonElement prs = new JsonParser().parse(jsonString); 

It has methods for checking the entity type in json. For example:

 prs.isJsonObject() prs.isJsonArray() 

and so on.

Due to this, you can manually walk through the elements of json'a and get the information you need. There must be something similar in other json parsers.

  • With an array of understandable. And you can refer to the N-th member of the object? By index for example? If I don’t know its structure for sure - ravend
  • one
    You can iterate over fields: prs.getAsJsonObject (). EntrySet (), where the result is Set <Entry <String, JsonElement >> - Anver Bogatov