Encode and Decode JSON text from Java to JavaScript – Using List

JSON.simple is a simple Java toolkit for JSON. You can use JSON.simple to encode or decode JSON text.

  1. Mapping between JSON and JAVA entities: 
    JSON Java
    string java.lang.String
    number java.lang.Number
    true|false java.lang.Boolean
    null null
    array java.util.List
    object java.util.Map
  2. Example:
    //import org.json.simple.JSONObject;
    Encode a java.util.List in Java
    Java:

      JSONObject obj = new JSONObject();
      obj.put("name","foo");
      obj.put("num",new Integer(100));
      obj.put("balance",new Double(1000.21));
      obj.put("is_vip",new Boolean(true));
      obj.put("nickname",null);
    
      String jsonText = JSONValue.toJSONString(obj);

    Decode it in JavaScript using JSONObject

    JavaScript:

      var js_obj = JQuery.parseJSON(jsonText);
      var name = js_obj[0].name;
      var num = js_obj[0].num;

Reference Link: https://code.google.com/p/json-simple/
Reference Link: http://api.jquery.com/jQuery.parseJSON/
Reference Link: http://www.jquerysdk.com/api/jQuery.toJSON

Advertisements

Java – List Example

List example give a method, how to use List in java:

  1. Code:
    import java.util.Iterator;
    import java.util.List;
    import java.util.ArrayList;
    
    public class ListExample {
    
        public static void main(String[] args) {
    
            // List Example implement with ArrayList
            List<String> ls=new ArrayList<String>();
    
            ls.add("one");
            ls.add("Three");
            ls.add("two");
            ls.add("four");
    
            Iterator it=ls.iterator();
    
            while(it.hasNext())
            {
              String value=(String)it.next();
    
              System.out.println("Value :"+value);
            }
        }
    }
  2. Output:
    List Value :One
    List Value :Three
    List Value :two
    List Value :four

Reference Link: http://www.easywayserver.com/blog/java-list-example/

How to convert string to (double, int or boolean) and int to String in Java

With this code, you can convert string to double or to int or to boolean and convert int to string in Java:

  1. Convert string to int:
    String aString = "78";
    int aInt = Integer.parseInt(aString);
  2. Convert string to double:
    String aString = "78";
    double aDouble = Double.parseDouble(aString);
  3. Convert string to boolean:
    String aString = "true";
    double aBoolean = Boolean.valueOf(aString);
  4. Convert int to string:
    int aInt = 1;    
    String aString = Integer.toString(aInt);
  5. Convert double to string:
    double aDouble = 1.0;    
    String aString = Double.toString(aDouble);