0

I used jackson to convert json strings to json objects / arrays like so:

JSONObject jsonObj = XML.toJSONObject(myXmlString);
JSONObject userObj = jsonObj.getJSONObject("user"); // is there a GSON version of this? 
JSONArray orders = userObj.getJSONArray("orders");

My main question is: is there a GSON version of getting json objects / arrays without converting to a pojo? My json is very complex so it's difficult to create pojos.

Secondly, does gson allow you to convert an xml string to json like jackson does (line 1)?

  • Instead of using POJOs you might want to try deserializing json into HashMap. I do this in my projects and everything works fine. To get to the values of HashMap you need to know they predefined keys tho – Max Urbanowicz Dec 18 '19 at 10:22

2 Answers2

0

For the first question:

You can create a JsonObject from a json string

String json = "{ \"key1\": \"value1\", \"key2\": false}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

otherwise you can create a Map object

String jsonString = "{'employee.name':'Bob','employee.salary':10000}";
Gson gson = new Gson();
Map map = gson.fromJson(jsonString, Map.class);

for reference: https://www.baeldung.com/gson-json-to-map

For the second question:

I found this question in stackoverflow

Margon
  • 511
  • 2
  • 10
  • 2
    Did you read what he need, before writing the code , you should read the question well – Dulaj Kulathunga Dec 18 '19 at 10:26
  • what do you mean? My answer is exactly what he needs (?), he has json string that must be converted with GSON, without using a POJO. My code does exactly that. Did I miss something obvious? – Margon Dec 18 '19 at 10:30
  • For the second one, I can't use jaxb unfortunately. Don't think GSON can do this alone? –  Dec 18 '19 at 10:30
0

is there a GSON version of getting json objects / arrays without converting to a pojo?

Something like this can do the job

import com.google.gson.*;

JsonParser parser = new JsonParser();

JsonElement json = parser.parse(myJsonString);

//get as object
JsonObject obj = json.getAsJsonObject();

//get as array
JsonArray arr = json.getAsJsonArray();

does gson allow you to convert an xml string to json like jackson does

No

rkosegi
  • 14,165
  • 5
  • 50
  • 83