All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.ralfspoeth.json.JsonObject Maven / Gradle / Ivy

Go to download

This project implements a JSON parser and serializer which operates around immutable data structures for the JSON elements.

There is a newer version: 1.1.6
Show newest version
package io.github.ralfspoeth.json;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.RecordComponent;
import java.util.Map;
import java.util.function.Function;

import static io.github.ralfspoeth.json.Aggregate.objectBuilder;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toMap;

public record JsonObject(Map members) implements Aggregate, Function {

    public JsonObject {
        members = Map.copyOf(members);
    }

    public static  JsonObject ofRecord(R r) {
        var rc = r.getClass().getRecordComponents();
        var ob = objectBuilder();
        for (RecordComponent comp : rc) {
            var name = comp.getName();
            try {
                var value = comp.getAccessor().invoke(r);
                ob.named(name, Element.of(value));
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
        return ob.build();
    }

    public static JsonObject asJsonObject(Map map) {
        var members = map.entrySet()
                .stream()
                .collect(toMap(String::valueOf, Element::of));
        return new JsonObject(members);
    }

    @Override
    public int size() {
        return members.size();
    }

    @Override
    public int depth() {
        return members.values().stream().mapToInt(v ->
            switch (v) {
                case Aggregate a -> a.depth();
                case Basic ignored -> 1;
            }
        ).max().orElse(0)+1;
    }

    public  T get(String name, Class cls) {
        return ofNullable(members.get(name)).map(cls::cast).orElse(null);
    }

    @Override
    public Element apply(String name) {
        return members.get(name);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy