Error in converting List to JSON in Java (2), javajson
1. Error description
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactoryat net.sf.json.AbstractJSON.<clinit>(AbstractJSON.java:53)at com.you.model.ListToJSON.main(ListToJSON.java:29)Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactoryat java.net.URLClassLoader$1.run(URLClassLoader.java:366)at java.net.URLClassLoader$1.run(URLClassLoader.java:355)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:354)at java.lang.ClassLoader.loadClass(ClassLoader.java:425)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)at java.lang.ClassLoader.loadClass(ClassLoader.java:358)... 2 more
2. Error cause
/*** Convert List to JSON */package com. you. model; import java. util. arrayList; import java. util. list; import net. sf. json. JSONArray;/*** @ author YouHaiDong **/public class ListToJSON {/*** @ param args */public static void main (String [] args) {List <String> list = new ArrayList <String> (); list. add ("Spring"); list. add ("Summer"); list. add ("Autumn"); list. add ("Winter"); JSONArray jsonArray = JSONArray. fromObject (list); System. out. println ("List converted to JSON:" + jsonArray. toString ());}}
We can see from "Caused by: java. lang. ClassNotFoundException: org. apache. commons. logging. LogFactory" that jar is missing.
3. Solution
Copy commons-logging-1.1.3.jar to lib
How to convert list into json in java
// Need to use json-lib.jar, you can download here: json-lib.sourceforge.net/
// Code instance
List <String> list = new ArrayList <String> ();
List. add ("abc ");
List. add ("123 ");
Net. sf. json. JSONArray jsonArray = net. sf. json. JSONArray. fromObject (list );
System. out. println (jsonArray. toString ());
Conversion from List set to json in java
Exception has told you, obviously the package is missing, should be missing the commons-beanutils.jar File