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

com.rathravane.till.data.json.JsonUtil Maven / Gradle / Ivy

package com.rathravane.till.data.json;

import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.rathravane.till.data.json.JsonVisitor.ArrayOfStringVisitor;
import com.rathravane.till.data.json.JsonVisitor.ObjectVisitor;

public class JsonUtil
{
	public static JSONObject clone ( JSONObject that )
	{
		if ( that == null ) return null;

		final JSONObject result = new JSONObject ();
		JsonVisitor.forEachElement ( that, new ObjectVisitor ()
		{
			@Override
			public boolean visit ( String key, Object value ) throws JSONException
			{
				result.put ( key, value );
				return true;
			}
		} );
		return result;
	}

	public static void copyInto ( JSONObject src, final JSONObject dest )
	{
		if ( src == null || dest == null ) return;

		JsonVisitor.forEachElement ( src, new ObjectVisitor ()
		{
			@Override
			public boolean visit ( String key, Object value ) throws JSONException
			{
				dest.put ( key, value );
				return true;
			}
		} );
	}

	public static int getIndexOfStringInArray ( String s, JSONArray a )
	{
		if ( a == null || s == null ) return -1;

		int found = -1;
		for ( int i=0; i -1 )
		{
			a.remove ( found );
			return true;
		}

		return false;
	}

	/**
	 * Load a string or array of strings into a string list.
	 * 
	 * @param base the base json object
	 * @param key the key of the string array
	 * @return a list of 0 or more strings
	 * @throws JSONException if the key doesn't exist, or if it's not a string or array of strings
	 */
	public static List readStringArray ( JSONObject base, String key ) throws JSONException
	{
		final LinkedList result = new LinkedList ();

		final Object oo = base.opt ( key );
		if ( oo == null ) throw new JSONException ( key + " does not exist" );

		if ( oo instanceof JSONArray )
		{
			JsonVisitor.forEachStringElement ( (JSONArray)oo, new ArrayOfStringVisitor () 
			{
				@Override
				public boolean visit ( String str ) throws JSONException
				{
					result.add ( str );
					return true;
				}
			} );
		}
		else
		{
			result.add ( oo.toString () );
		}

		return result;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy