|
| 1 | +package com.annimon.ownlang.lib; |
| 2 | + |
| 3 | +import java.util.Iterator; |
| 4 | +import java.util.Map; |
| 5 | +import org.json.JSONArray; |
| 6 | +import org.json.JSONObject; |
| 7 | + |
| 8 | +public final class ValueUtils { |
| 9 | + |
| 10 | + public static Object toObject(Value val) { |
| 11 | + switch (val.type()) { |
| 12 | + case Types.ARRAY: |
| 13 | + return toObject((ArrayValue) val); |
| 14 | + case Types.MAP: |
| 15 | + return toObject((MapValue) val); |
| 16 | + case Types.NUMBER: |
| 17 | + return val.raw(); |
| 18 | + case Types.STRING: |
| 19 | + return val.asString(); |
| 20 | + default: |
| 21 | + return JSONObject.NULL; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public static Object toObject(MapValue map) { |
| 26 | + final JSONObject result = new JSONObject(); |
| 27 | + for (Map.Entry<Value, Value> entry : map) { |
| 28 | + final String key = entry.getKey().asString(); |
| 29 | + final Object value = toObject(entry.getValue()); |
| 30 | + result.put(key, value); |
| 31 | + } |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + public static Object toObject(ArrayValue array) { |
| 36 | + final JSONArray result = new JSONArray(); |
| 37 | + for (Value value : array) { |
| 38 | + result.put(toObject(value)); |
| 39 | + } |
| 40 | + return result; |
| 41 | + } |
| 42 | + |
| 43 | + public static Value toValue(Object obj) { |
| 44 | + if (obj instanceof JSONObject) { |
| 45 | + return toValue((JSONObject) obj); |
| 46 | + } |
| 47 | + if (obj instanceof JSONArray) { |
| 48 | + return toValue((JSONArray) obj); |
| 49 | + } |
| 50 | + if (obj instanceof String) { |
| 51 | + return new StringValue((String) obj); |
| 52 | + } |
| 53 | + if (obj instanceof Number) { |
| 54 | + return NumberValue.of(((Number) obj)); |
| 55 | + } |
| 56 | + if (obj instanceof Boolean) { |
| 57 | + return NumberValue.fromBoolean((Boolean) obj); |
| 58 | + } |
| 59 | + // NULL or other |
| 60 | + return NumberValue.ZERO; |
| 61 | + } |
| 62 | + |
| 63 | + public static MapValue toValue(JSONObject json) { |
| 64 | + final MapValue result = new MapValue(json.length()); |
| 65 | + final Iterator<String> it = json.keys(); |
| 66 | + while(it.hasNext()) { |
| 67 | + final String key = it.next(); |
| 68 | + final Value value = toValue(json.get(key)); |
| 69 | + result.set(new StringValue(key), value); |
| 70 | + } |
| 71 | + return result; |
| 72 | + } |
| 73 | + |
| 74 | + public static ArrayValue toValue(JSONArray json) { |
| 75 | + final int length = json.length(); |
| 76 | + final ArrayValue result = new ArrayValue(length); |
| 77 | + for (int i = 0; i < length; i++) { |
| 78 | + final Value value = toValue(json.get(i)); |
| 79 | + result.set(i, value); |
| 80 | + } |
| 81 | + return result; |
| 82 | + } |
| 83 | +} |
0 commit comments