如何在java中序列化JSON对象

前端之家收集整理的这篇文章主要介绍了如何在java中序列化JSON对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我正在使用Voldemort来存储我的数据.我的关键是一个单词,值是单词和URL的出现次数.例如:
  1. key :question
  2. value: 10,www.stackoverflow.com

我正在使用Json对象来放置我的值.
我的代码看起来像这样

  1. import org.json.JSONObject;
  2. import com.Metaparadigm.jsonrpc.JSONSerializer;
  3. import voldemort.client.ClientConfig;
  4. import voldemort.client.SocketStoreClientFactory;
  5. import voldemort.client.StoreClient;
  6. import voldemort.client.StoreClientFactory;
  7.  
  8. public class ClientExample {
  9. public static void main (String [] args) {
  10. String bootstrapUrl = "tcp://localhost:6666";
  11.  
  12. ClientConfig cc = new ClientConfig ();
  13. cc.setBootstrapUrls (bootstrapUrl);
  14. String[] valuePair = new String[2];
  15. int val = 1;
  16. StoreClientFactory factory = new SocketStoreClientFactory (cc);
  17. StoreClient client = factory.getStoreClient("test");
  18. JSONObject json = new JSONObject();
  19. json.put("occurence",val);
  20. json.put("url","www.cnn.com");
  21. client.put("foo",json);
  22. }
  23. }

我的store.xml看起来像这样

  1. <stores>
  2. <store>
  3. <name>test</name>
  4. <persistence>bdb</persistence>
  5. <routing>client</routing>
  6. <replication-factor>1</replication-factor>
  7. <required-reads>1</required-reads>
  8. <required-writes>1</required-writes>
  9. <key-serializer>
  10. <type>string</type>
  11. </key-serializer>
  12. <value-serializer>
  13. <type>java-serialization</type>
  14. <schema-info>"Compount Types"</schema-info>
  15. </value-serializer>
  16. </store>
  17. </stores>

当我试图运行代码时,我得到以下异常:
**

Exception in thread “main”
voldemort.serialization.SerializationException:
java.io.NotSerializableException:

org.json.JSONObject at
voldemort.serialization.ObjectSerializer.toBytes(ObjectSerializer.java:47)
at
voldemort.store.serialized.SerializingStore.put(SerializingStore.java:109)
at
voldemort.store.DelegatingStore.put(DelegatingStore.java:68)
at
voldemort.client.DefaultStoreClient.put(DefaultStoreClient.java:208)
at
voldemort.client.DefaultStoreClient.put(DefaultStoreClient.java:193)
at
ClientExample.main(ClientExample.java:27)
Caused by:
java.io.NotSerializableException:
org.json.JSONObject at
java.io.ObjectOutputStream.writeObject0(Unknown
Source) at
java.io.ObjectOutputStream.writeObject(Unknown
Source) at
voldemort.serialization.ObjectSerializer.toBytes(ObjectSerializer.java:44)

**

你能否告诉我如何序列化JSON对象.提前谢谢.

解决方法

看看 Gson库.它对对象映射和序列化做了很好的JSON.

猜你在找的Java相关文章