1. JSON-LIB est une bibliothèque de classe Java qui fournit la fonction de convertir des objets Java, y compris des haricots, des cartes, des collections, des tableaux Java et du XML, en JSON ou une conversion inverse.
2. Page d'accueil JSON-LIB: http://json-lib.sourceforge.net/
3. Environnement d'exécution
Le support de bibliothèque suivant est requis
Commons-Lang 2.5
Commons-Beanutils 1.8.0
COMMONS-COLLECTIONS 3.2.1
Commons-Logging 1.1.1
ezmorph 1.0.6
4. Exemples fonctionnels
Voici un exemple de code donné par l'exemple Junit-Case
La copie de code est la suivante:
Package com.mai.json;
Importer Static Org.Junit.Assert.AsserTequals;
import java.util.arraylist;
Importer java.util.date;
import java.util.hashmap;
Importer java.util.iterator;
Importer java.util.list;
importation java.util.map;
importer net.sf.ezmorph.morpher;
importer net.sf.ezmorph.morpherRegistry;
importer net.sf.ezmorph.bean.beanmorpher;
importer net.sf.json.jsonArray;
importer net.sf.json.jsonObject;
importer net.sf.json.util.jsonutils;
import org.apache.commons.beanutils.propertyutils;
import org.junit.test;
classe publique jsonlibtest {
/ *
* Les types normaux, la liste, la collection, etc. sont tous analysés à l'aide de JSONArray
*
* Les types de cartes et de personnaux sont analysés à l'aide de JSONObject
* La carte peut être comprise comme un objet, et les paires de clé / valeur à l'intérieur peuvent être comprises comme les valeurs d'attributs / d'attribut de l'objet
* C'est {key1: value1, key2, value2 ...}
*
* 1. JSONObject est un nom: la collecte des valeurs.
* Grâce à son getjsonObject (clé), vous pouvez obtenir un jsonObject, -> convertir en map,
* Grâce à son getjsonArray (clé), vous pouvez obtenir un jsonArray,
*
*
* /
// convertit généralement les tableaux en JSON
@Test
public void TestArraytojson () {
Boolean [] boolArray = new Boolean [] {true, false, true};
JSONArray JSONArray = JSONArray.FromObject (BoolArray);
System.out.println (JSONArray);
// imprime [true, false, true]
}
// Convertir l'objet de collection en JSON
@Test
public void TestListTojson () {
List list = new ArrayList ();
list.add ("premier");
list.add ("second");
JSONArray JSONArray = JSONArray.FromObject (liste);
System.out.println (JSONArray);
// imprime ["First", "Second"]
}
// Convertir la chaîne JSON en JSON, selon la situation, utilisez JSONArray ou JSONObject
@Test
public void testJSontrtojson () {
JSONArray JSONArray = JSONArray.FromObject ("['JSON', 'IS', 'Easy']");
System.out.println (JSONArray);
// imprime ["json", "est", "facile"]
}
// Convertir la carte en JSON, en utilisant JSONObject
@Test
public void testmaptojson () {
Map map = new HashMap ();
map.put ("name", "json");
map.put ("bool", boolean.true);
map.put ("int", nouvel entier (1));
map.put ("arr", nouvelle chaîne [] {"a", "b"});
map.put ("func", "function (i) {return this.arr [i];}");
JSONObject JSONObject = JSONObject.FromObject (Map);
System.out.println (jsonObject);
}
// Type de composé Bean dans JSON
@Test
public void testbeadtojson () {
MyBean Bean = new MyBean ();
bean.setid ("001");
bean.setname ("carte bancaire");
bean.setDate (new Date ());
List cardnum = new ArrayList ();
cardnum.add ("Banque agricole");
cardnum.add ("icbc");
cardnum.add ("ccb");
cardnum.add (nouvelle personne ("test"));
bean.setcardnum (cardnum);
JSONObject JSONObject = JSONObject.FromObject (Bean);
System.out.println (jsonObject);
}
// convertir JSON de type normal en objet
@Test
public void testjSontoObject () lève une exception {
String JSON = "{name = /" JSON / ", bool: true, int: 1, double: 2.2, fonction: function (a) {return a;}, array: [1,2]}";
JSONObject JSONObject = JSONObject.FromObject (JSON);
System.out.println (jsonObject);
Objet bean = jsonObject.tobean (jsonObject);
asserTequals (jsonObject.get ("name"), propriété.getProperty (bean, "name"));
asserTequals (jsonObject.get ("bool"), propertyUtils.getProperty (bean, "bool"));
asserTequals (jsonObject.get ("int"), propertyUtils.getProperty (bean, "int"));
asserTequals (jsonObject.get ("double"), propertyUtils.getProperty (bean, "double"));
asserTequals (jsonObject.get ("func"), propertyUtils.getProperty (bean, "func"));
System.out.println (PropertyUtils.getProperty (Bean, "Name"));
System.out.println (PropertyUtils.getProperty (Bean, "Bool"));
System.out.println (PropertyUtils.getProperty (Bean, "int"));
System.out.println (PropertyUtils.getProperty (Bean, "Double"));
System.out.println (PropertyUtils.getProperty (Bean, "Func"));
System.out.println (PropertyUtils.getProperty (Bean, "Array"));
List arrayList = (list) jsonArray.tocollection (jsonObject.getjsonArray ("array"));
pour (objet objet: arrayList) {
System.out.println (objet);
}
}
// Analyser JSON dans un objet de type composite, y compris la liste
@Test
public void testjSontobeanhavalist () {
String json = "{list: [{name: 'test1'}, {name: 'test2'}], map: {test1: {name: 'test1'}, test2: {name: 'test2'}}}" ;
// String json = "{list: [{name: 'test1'}, {name: 'test2'}]}";
Map classMap = new Hashmap ();
classmap.put ("list", personne.class);
MyBeanWithPerson Diybean = (MyBeanWithPerson) JSONObject.Tobean (JSONObject.FromObject (JSON), MyBeanWithPerson.Class, ClassMap);
System.out.println (Diybean);
List list = diybean.getList ();
pour (objet o: list) {
if (o instanceof personne) {
Personne p = (personne) o;
System.out.println (P.GetName ());
}
}
}
// Analyser JSON dans un objet de type composite, y compris la carte
@Test
public void testjSontobeanHavamap () {
// Considérez la carte comme un objet
String json = "{list: [{name: 'test1'}, {name: 'test2'}], map: {testone: {name: 'test1'}, testtwo: {name: 'test2'}}}" ;
Map classMap = new Hashmap ();
classmap.put ("list", personne.class);
classmap.put ("map", map.class);
// Utilisez un indice, analyser directement JSON dans un objet personnalisé spécifié, où la liste est entièrement analysée, la carte n'est pas entièrement analysée
MyBeanWithPerson Diybean = (MyBeanWithPerson) JSONObject.Tobean (JSONObject.FromObject (JSON), MyBeanWithPerson.Class, ClassMap);
System.out.println (Diybean);
System.out.println ("Faire la version de la liste");
List <onon> list = diybean.getList ();
pour (personne o: liste) {
Personne p = (personne) o;
System.out.println (P.GetName ());
}
System.out.println ("Do the Map Release");
// Enregistrez d'abord le transformateur dans le registre et vous devez utiliser la classe dans le package Ezmorph
MorPherRegistry MorPherRegistry = jsonUtils.getMorPherRegistry ();
Morpher Dynamorpher = new BeanMorpher (Person.class, MorPherRegistry);
morpherRegistry.RegisterMorpher (Dynamorpher);
Map map = diybean.getmap ();
/ * La carte ici n'a pas d'indices de type, donc selon la valeur par défaut, l'objet stocké est un type net.sf.ezmorph.bean.morphdynabean * /
System.out.println (MAP);
/*Sortir:
{testone=net.sf.ezmorph.bean.morphdynabean@f73c1 [
{name = test1}
], testtwo=net.sf.ezmorph.bean.morphdynabean@186c6b2 [
{name = test2}
]}
* /
List <ponge> output = new ArrayList ();
for (iterator i = map.values (). iterator (); i.hasnext ();) {
// Utilisez le registraire pour effectuer une transformation d'objet sur la dynabéenne spécifiée
output.add ((personne) morpherRegistry.morph (personne.class, i.next ()));
}
pour (personne P: sortie) {
System.out.println (P.GetName ());
/*Sortir:
test1
test2
* /
}
}
}
5. Les éléments suivants fournissent les ressources requises pour l'exemple ci-dessus, y compris les packages en pot et le code
/ Fichiers / maillingfeng / json-lib / json-lib le cas d'utilisation nécessite des packages JAR et des classes Java.rar