#Map to Json

1 messages · Page 1 of 1 (latest)

mental trail
#

Hi guys don't you even know how i can convert the Map<?,?> to Json?
Map
{null={"player":{"name":"pepa","age":11,"op":false,"data":[10,100]}}, player={null={"name":"pepa","age":11,"op":false,"data":[10,100]}, age=11.0, data={null=[10,100], 1=10.0, 2=100.0, 3=20}, name=pepa, op=false}}

Expected json

{"player":{"name":"pepa","age":11,"op":false,"data":[10,100,20]}}
forest quartzBOT
#

<@&987246584574140416> please have a look, thanks.

forest quartzBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

tough crystal
#

If you're trying to convert a Java object to JSON you will need to use a JSON library, I recommend GSON: https://github.com/google/gson.

In GSON turning a map to JSON is pretty simple:

Gson gsonObj = new Gson();
Map<String, String> jobs = new HashMap<String, String>();
inputMap.put("John", "Architect");
inputMap.put("Pam", "Doctor");
String jsonStr = gsonObj.toJson(inputMap);
forest quartzBOT
forest quartzBOT
neat patio
#

@mental trail hey! i know how

#

though that null= is ..difficult

mental trail
neat patio
#

null is not a valid json key

#

where do you have the Map<?, ?>?

mental trail
#
[00:13:52 INFO]:
[00:13:52 INFO]: {
[00:13:52 INFO]:   "another": [
[00:13:52 INFO]:     0.0
[00:13:52 INFO]:   ],
[00:13:52 INFO]:   "another2": {
[00:13:52 INFO]:     "b": 2.0
[00:13:52 INFO]:   },
[00:13:52 INFO]:   "player": {
[00:13:52 INFO]:     "age": 11.0,
[00:13:52 INFO]:     "data": {
[00:13:52 INFO]:       "1": 10.0,
[00:13:52 INFO]:       "2": 100.0,
[00:13:52 INFO]:       "3": 20,
[00:13:52 INFO]:       "4": 30
[00:13:52 INFO]:     },
[00:13:52 INFO]:     "name": "pepa",
[00:13:52 INFO]:     "op": false
[00:13:52 INFO]:   }
[00:13:52 INFO]: }
#

this is my new output

mental trail
neat patio
#

err

#

not sure what you are asking

#

how did you end up with a Map<?, ?>?

mental trail
#
DEBUG! Variable: {another={1=0.0}, another2={b=2.0}, player={age=11.0, data={1=10.0, 2=100.0, 3=20, 4=30}, name=pepa, op=false}}
DEBUG! OBJECT: {"another":[0.0],"another2":{"b":2.0},"player":{"age":11.0,"data":{"1":10.0,"2":100.0,"3":20,"4":30},"name":"pepa","op":false}}
#

I'm still using it, but I fixed the null error. but now I can't convert the Array correctly.

neat patio
#

....

#

okay again I ask you

#

how did you end up with a map<?, ?>

#

if you are following that gson snippet you can use a list for the data and it will work

#

but

#

how did you end up with a map<?, ?>

mental trail
#

I don't use the gson snippet at all, like I still have the code I sent, they just keep editing it, the current form is this.

        public static JsonElement listToJson(Event event, String name, boolean isLocal) {
            JsonElement json = null;

            Object next;
            Deque<Object> objects = new ArrayDeque<>();
            Map<String, Object> variable = (Map<String, Object>) getVariable(event, name + "*", isLocal);
            if (variable == null) return new JsonNull();
            JsonElement finalJson;

            SkriptGson.debug("&aVariable: &r"+variable);
            if (variable.keySet().stream().filter(Objects::nonNull).allMatch(Utils::isNumeric)) {
                finalJson = new JsonArray();
            } else {
                finalJson = new JsonObject();
            }


            objects.add(variable);

            while ((next = objects.pollFirst()) != null)
            {
                Stream<String> keys = ((Map<String, Object>) next).keySet().stream().filter(Objects::nonNull);
                Object finalNext = next;
                keys.forEach(key -> {
                    JsonElement element = hierarchyAdapter().toJsonTree(((Map<?, ?>) finalNext).get(key));

                    SkriptGson.debug("Key: "+key);
                    SkriptGson.debug("&aValue: "+element);

                    if (!(element instanceof JsonArray || element instanceof JsonObject))
                    {
                        if (finalJson.isJsonObject())
                        {
                            finalJson.getAsJsonObject().add(key, element);
                        } else if (finalJson.isJsonArray())
                        {
                            finalJson.getAsJsonArray().add(element);
                        }
                    }
                    else
                    {
                        if (finalJson.isJsonObject())
                        {
                            objects.offerLast(element.getAsJsonObject().asMap());
                        } else if (finalJson.isJsonArray())
                        {
                            objects.offerLast(element.getAsJsonArray().asList());
                        }
                    }
                });
            }
            System.out.println(finalJson);
            return null;
        }
    }
forest quartzBOT
neat patio
#

okay

#

what is this getVariable

mental trail
#
    public static Object getVariable(Event e, String name, boolean isLocal) {
        final Object variable = Variables.getVariable(name, e, isLocal);
        if (variable == null) {
            return Variables.getVariable((isLocal ? Variable.LOCAL_VARIABLE_TOKEN : "") + name, e, false);
        }
        return variable;
    }
forest quartzBOT
mental trail
#

it's from a SkriptLang.

neat patio
#

gotcha

#

so it represents lists as maps of numbers to items?

#

thats cursed

#

what java version are you using?

mental trail
#

16

neat patio
#

cool

#

one second

#
private static JsonElement skriptElementToJson(Object o) {
    if (o == null) {
        return new JsonNull();
    }
    else if (o instanceof Map<?, ?> map) {
        if (map.keySet().stream().filter(Objects::nonNull).allMatch(Utils::isNumeric)) {
            var array = new JsonArray();
            map.values().forEach(key -> {
                array.add(skriptElementToJson(map.get(key));
            });
            return array;
        }
        else {
            var object = new JsonObject();
            map.entrySet().forEach(entry -> {
                if (entry.getKey() instanceof String stringKey) {
                    object.add(stringKey, skriptElementToJson(entry.getValue());
                }
            });
            return object;
        }
    }
    else if (o instanceof List<?> list) {
        var array = new JsonArray();
        for (var item : list) {
            array.add(skriptElementToJson(item));
        }
        return array;
    }
    else if (o instanceof Number number) {
        // ...
    }
    else if (o instanceof String string) {
        // ...
    }
    else if (o instanceof Boolean bool) {
        // ...
    }
    
    throw new IllegalStateException("unhandled value type: " + o.getClass());
}
#

so the difference here is instead of having a Deque you just have a recursive function

#

and you can box up all the logic like this, basically

#

so if you can fill in the blanks the rest of the code just looks like

#
var variable = getVariable(event, name + "*", isLocal);
return skriptElementToJson(variable);