tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 JSON > JSON LIB > Collection to JSON Array

Collection to JSON Array 

JSON-lib is a java library for serializing and de-serializing java beans, maps, arrays and collections in JSON format. Get the latest binaries from sourceforge http://json-lib.sourceforge.net/. This requires the libraries ( json-lib-2.4-jdk15.jar, xom-1.2.7.jar, ezmorph.jar commons-lang.jar, commons-collections.jar, commons-beanutils-1.7.jar and commons-logging-1.1.1.jar) to be in classpath. The following example shows converting a Collection to JSON Array.

File Name  :  
com/bethecoder/tutorials/json_lib/tests/Collection2JsonArray.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.json_lib.tests;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;

public class Collection2JsonArray {

  /**
   @param args
   */
  public static void main(String[] args) {
    List<String> strs = Arrays.asList("one""two""three""four");
    JSONArray jsonArray = (JSONArrayJSONSerializer.toJSON(strs);
    System.out.println(jsonArray.toString(2))//pretty print with indent
    
    List<Object> genList = new ArrayList<Object>();
    genList.add("one");
    genList.add(new Integer(2));
    genList.add(new Long(3));
    genList.add(new Double(4.26));
    genList.add(true);
    genList.add(new char [] { 'A''B''C' });
    
    jsonArray = (JSONArrayJSONSerializer.toJSON(genList);
    System.out.println(jsonArray.toString(2))//pretty print with indent
  }

}
   

It gives the following output,
[
  "one",
  "two",
  "three",
  "four"
]


[
  "one",
  2,
  3,
  4.26,
  true,
    [
    "A",
    "B",
    "C"
  ]
]


                    Print

   



Books Recommendation

 
 
bl  br