tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 JSON > JSON JAVA > JSON Keys

JSON Keys 

JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. Douglas Crockford has provided a reference implementation of JSON in Java at http://json.org/ useful for JSON serialization and deserialization. Click here to download the compiled library. The following example shows getting the keys of a simple JSON object.

File Name  :  
com/bethecoder/tutorials/json_java/common/Student.java 
   
package com.bethecoder.tutorials.json_java.common;

import java.util.Date;

public class Student {
  private String firstName;
  private String lastName;
  private int age;
  private String hobby;
  private Date dob;

  public Student(String firstName, String lastName, int age, String hobby,
      Date dob) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.hobby = hobby;
    this.dob = dob;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }

  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  public Date getDob() {
    return dob;
  }
  public void setDob(Date dob) {
    this.dob = dob;
  }

}
   

File Name  :  
com/bethecoder/tutorials/json_java/tests/JsonKeys.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.json_java.tests;

import java.util.Arrays;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import com.bethecoder.tutorials.json_java.common.Student;

public class JsonKeys {

  /**
   @param args
   @throws JSONException 
   */
  public static void main(String[] argsthrows JSONException {
    Student stud = new Student("Sriram""Kasireddi"2"Singing"new Date(11046));
    JSONObject obj = new JSONObject(stud);
    System.out.println(obj.toString(2))//pretty print with indent
    
    /**
     * Get the names array
     */
    System.out.println(Arrays.toString(JSONObject.getNames(obj)));
  }

}
   

It gives the following output,
{
  "lastName": "Kasireddi",
  "dob": "Thu May 06 00:00:00 IST 2010",
  "age": 2,
  "hobby": "Singing",
  "firstName": "Sriram"
}

[lastName, dob, age, hobby, firstName]



 
  


  
bl  br