diff src/luan/Luan.java @ 1113:22652f4020fb

add JsonToString
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 02 Aug 2017 19:00:24 -0600
parents 1a68fc55a80c
children 1f9d34a6f308
line wrap: on
line diff
--- a/src/luan/Luan.java	Wed Aug 02 17:37:59 2017 -0600
+++ b/src/luan/Luan.java	Wed Aug 02 19:00:24 2017 -0600
@@ -1,6 +1,12 @@
 package luan;
 
 import java.util.List;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.LinkedHashMap;
+import java.util.Set;
+import java.util.Arrays;
+import java.util.Iterator;
 import luan.modules.BasicLuan;
 import luan.impl.LuanCompiler;
 
@@ -153,5 +159,70 @@
 	}
 
 
+	public static Object toLuan(Object obj) throws LuanException {
+		if( !type(obj).equals("java") )
+			return obj;
+		LuanTable tbl = new LuanTable();
+		if( obj instanceof Map ) {
+			Map map = (Map)obj;
+			for( Object stupid : map.entrySet() ) {
+				Map.Entry entry = (Map.Entry)stupid;
+				Object key = entry.getKey();
+				Object value = entry.getValue();
+				if( key != null && value != null )
+					tbl.rawPut(toLuan(key),toLuan(value));
+			}
+			return tbl;
+		}
+		if( obj instanceof Set ) {
+			Set set = (Set)obj;
+			for( Object el : set ) {
+				if( el != null )
+					tbl.rawPut(toLuan(el),Boolean.TRUE);
+			}
+			return tbl;
+		}
+		List list;
+		if( obj instanceof List ) {
+			list = (List)obj;
+		} else {
+			Class cls = obj.getClass();
+			if( cls.isArray() && !cls.getComponentType().isPrimitive() ) {
+				Object[] a = (Object[])obj;
+				list = Arrays.asList(a);
+			} else
+				throw new LuanException("can't convert type "+obj.getClass().getName()+" to luan");
+		}
+		int n = list.size();
+		for( int i=0; i<n; i++ ) {
+			Object val = list.get(i);
+			if( val != null )
+				tbl.rawPut(i+1,toLuan(val));
+		}
+		return tbl;
+	}
+
+	public static Object toJava(Object obj) throws LuanException {
+		if( !(obj instanceof LuanTable) )
+			return obj;
+		LuanTable tbl = (LuanTable)obj;
+		if( tbl.isList() ) {
+			List list = new ArrayList();
+			for( Object el : tbl.asList() ) {
+				list.add( toJava(el) );
+			}
+			return list;
+		} else {
+			Map map = new LinkedHashMap();
+			Iterator<Map.Entry> iter = tbl.rawIterator();
+			while( iter.hasNext() ) {
+				Map.Entry entry = iter.next();
+				map.put( toJava(entry.getKey()), toJava(entry.getValue()) );
+			}
+			return map;
+		}
+	}
+
+
 	private Luan() {}  // never
 }