How can I convert a JSONObject to a gson.JsonObject?
Asked Answered
G

3

27

I have a org.json.JSONObject object.

What's the easiest way to create a gson.JsonObject object from it?

Thanks

Giltzow answered 6/8, 2015 at 22:29 Comment(0)
W
48

The easiest way is to serialize your JSONObject to a json string using toString(), then parsing that json string into a JsonObject:

    org.json.JSONObject object = <your defined object>;
    JsonParser jsonParser = new JsonParser();
    JsonObject gsonObject = (JsonObject)jsonParser.parse(object.toString());

Note that serializing and deserializing an object can be an expensive operation. If you have to do this a lot in your code (inside loops), it can affect your performance.

Weltpolitik answered 6/8, 2015 at 22:57 Comment(3)
is there a way to do the vice versa?Inexpiable
jsonParser.parse(object.toString()) is returning JsonElement object. I'm not able to cast it to org.json.JSONObject. I'm trying to convert from gson.JsonObject to org.json.JSONObject.Conventioner
@Marcelo Filho How about JSONObject jsonObject = new JSONObject(jsonObject.toString());Hydatid
B
0

in Kotlin use this extension:

fun JSONObject.toGsonJsonObject():JsonObject{
    return JsonParser().parse(this.toString()) as JsonObject
}
Betjeman answered 16/8, 2023 at 9:26 Comment(0)
D
0

JsonParser().parse(String) is deprecated functions instead use below

var object:JSONObject = {"key":"value"}
var json :JsonObject = JsonParser.parseString(object.toString()).asJsonObject
Dona answered 23/6 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.