Java tutorial
/* * cBean Copyright 2016, Tom Everett <tom@khubla.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.khubla.cbean.serializer.impl.json; import java.util.Hashtable; import java.util.Iterator; import org.json.JSONObject; import com.khubla.cbean.serializer.ClassHasher; import com.khubla.cbean.serializer.ObjectSerializer; import com.khubla.cbean.serializer.SerializerException; public class JSONObjectSerializer implements ObjectSerializer { private final ClassHasher classHasher; public JSONObjectSerializer(ClassHasher classHasher) { this.classHasher = classHasher; } @Override public Object deserialize(String str) throws SerializerException { try { final JSONObject jsonObject = new JSONObject(str); final Hashtable<String, String> hash = new Hashtable<String, String>(); final Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { final String key = keys.next(); final String value = jsonObject.getString(key); hash.put(key, value); } return classHasher.hashToClass(hash); } catch (final Exception e) { throw new SerializerException(e); } } @Override public String serialize(Object o) throws SerializerException { try { final Hashtable<String, String> hash = classHasher.classToHash(o); return new JSONObject(hash).toString(); } catch (final Exception e) { throw new SerializerException(e); } } }