chown -h myuser:mygroup mysymbolic


source - http://superuser.com/questions/68685/chown-is-not-changing-symbolic-link




Posted by linuxism
,


  • unable to insert data into mysql with JPA + Hibernate + Spring

    Not sure what i am doing wrong but i am unable to insert into into mysql database from code, 

    here is my configs 

    1. persistence.xml

    Code:
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    	version="1.0">
    	<persistence-unit name="profile"
    		transaction-type="RESOURCE_LOCAL">
    		 <provider>org.hibernate.ejb.HibernatePersistence</provider>
    		   <properties>
             <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
             <property name="hibernate.show_sql" value="true"></property>
          </properties>
          <class>com.xxx.core.entity.User</class>
    	</persistence-unit>
    </persistence>
    2. application-context.xml

    Code:
           <!-- Datasource -->
    	<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    		<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
    		<property name="url"><value>jdbc:mysql://localhost:3306/testdb</value></property>
    		<property name="username"><value>xxx</value></property>
    		<property name="password"><value>xxxx</value></property>
    	</bean>
    
        <!-- Entity Manager -->
    	<bean id="entityManagerFactory"
    		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="dataSource" ref="datasource" />
            <property name="persistenceUnitName" value="profile/>
    	</bean>
    
    	<!-- Transaction Manager -->
    	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="entityManagerFactory" />
    	</bean>
    
            <jpa:repositories base-package="com.xxx.repository"></jpa:repositories>
    
      <bean id="service"
    		class="com.xxx.UserServiceImpl">
    3. User.java

    Code:
    @Entity
    @Table(name = "user")
    public class User  implements Serializable{
    @Id
    	@Column(name = "id")
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	private Long id;
    	@Column(name = "user_name")
    
       // with get and set methods
    }
    4. UserServiceImpl.java

    Code:
    @Repository
    @Transactional(readOnly = true)
    public class UserServiceImpl implements UserService {
    	
    	@PersistenceContext
    	private EntityManager em;
    
    
    	@Override
    	public User save(User user) {
    		if (user.getId() == null) {
    			em.persist(user);
    			//User usr = em.find(User.class, new Long("3"));
    			System.out.println("user data=" + user.toString());
    			 return user;
    		} else {
    			return em.merge(user);
    		}
    	}
    
    	
    }
    Not sure what's the issue with above, but if i go to the sql workbench and insert data into the 'user' table i can fetch it by calling 

    Code:
    User usr = em.find(User.class, new Long("3"));
    any inputs is greatly appreciated, 

    Thanks 
    DP
  • just added below and it worked

    @Transactional(readOnly = true, propagation=Propagation.REQUIRED)



source - http://forum.spring.io/forum/spring-projects/data/128633-unable-to-insert-data-into-mysql-with-jpa-hibernate-spring








File: Employee.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity

public class Employee {
    @Id
    @Column(name="EMP_ID")
    private int id;
    private String name;

    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
   
}

File: Helper.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Helper {
  public static void checkData() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial""sa""");
    Statement st = conn.createStatement();

    ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
    while (mrs.next()) {
      String tableName = mrs.getString(3);
      System.out.println("\n\n\n\nTable Name: "+ tableName);

      ResultSet rs = st.executeQuery("select * from " + tableName);
      ResultSetMetaData metadata = rs.getMetaData();
      while (rs.next()) {
        System.out.println(" Row:");
        for (int i = 0; i < metadata.getColumnCount(); i++) {
          System.out.println("    Column Name: "+ metadata.getColumnLabel(i + 1)",  ");
          System.out.println("    Column Type: "+ metadata.getColumnTypeName(i + 1)":  ");
          Object value = rs.getObject(i + 1);
          System.out.println("    Column Value: "+value+"\n");
        }
      }
    }
  }
}

File: Main.java

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
  static EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAService");

  static EntityManager em = emf.createEntityManager();

  public static void main(String[] athrows Exception {
    em.getTransaction().begin();



    String query = "insert into Employee values(1,?)";

    em.createNativeQuery(query)
    .setParameter(1"Tom")
    .executeUpdate();

    em.getTransaction().commit();
    em.close();
    emf.close();

    Helper.checkData();
  }
}

File: persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence" version="1.0">
  <persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
      <property name="hibernate.connection.username" value="sa"/>
      <property name="hibernate.connection.password" value=""/>
      <property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
    </properties>
  </persistence-unit>
</persistence>



source - http://www.java2s.com/Tutorial/Java/0355__JPA/NativeInsertStatementWithParameter.htm








Getting started with Spring Data JPA

As we have just released the first milestone of the Spring Data JPA project I’d like to give you a quick introduction into its features. As you probably know, the Spring framework provides support to build a JPA based data access layer. So what does Spring Data JPA add to this base support? To answer that question I'd like to start with the data access components for a sample domain implemented using plain JPA + Spring and point out areas that leave room for improvement. After we've done that I will refactor the implementations to use the Spring Data JPA features to address these problem areas. The sample project as well as a step by step guide of the refactoring steps can be found on Github.

The domain

To keep things simple we start with a tiny well-known domain: we have Customers that haveAccounts.

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private String firstname;
  private String lastname;

  // … methods omitted
}
@Entity
public class Account {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @ManyToOne
  private Customer customer;

  @Temporal(TemporalType.DATE)
  private Date expiryDate;

  // … methods omitted
}

The Account has an expiry date that we will use at a later stage. Beyond that there's nothing really special about the classes or the mapping - it uses plain JPA annotations. Now let's take a look at the component managing Account objects:

@Repository
@Transactional(readOnly = true)
class AccountServiceImpl implements AccountService {

  @PersistenceContext
  private EntityManager em;

  @Override
  @Transactional
  public Account save(Account account) {

    if (account.getId() == null) {
      em.persist(account);
      return account;
    } else {
      return em.merge(account);
    }
  }

  @Override
  public List<Account> findByCustomer(Customer customer) {

    TypedQuery query = em.createQuery("select a from Account a where a.customer = ?1", Account.class);
    query.setParameter(1, customer);

    return query.getResultList();
  }
}

I deliberately named the class *Service to avoid name clashes as we will introduce a repository layer when we start refactoring. But conceptually the class here is a repository rather than a service. So what do we have here actually?

The class is annotated with @Repository to enable exception translation from JPA exceptions to Spring's DataAccessException hierarchy. Beyond that we use @Transactional to make sure the save(…) operation is running in a transaction and to allow setting the readOnly-flag (at the class level) for findByCustomer(…). This causes some performance optimizations inside the persistence provider as well as on the database level.

As we want to free the clients from the decision whether to call merge(…) or persist(…) on the EntityManager we use the id-field of the Account to decide whether we consider anAccount object as new or not. This logic could of course be extracted into a common superclass as we probably don't want to repeat this code for every domain object specific repository implementation. The query method is quite straight forward as well: we create a query, bind a parameter and execute the query to get a result. It's almost so straight forward that one could regard the implementation code as boilerplate as with a little bit of imagination it's derivable from the method signature: we expect a List of Accounts, the query is quite close to the method name and we simply bind the method parameter to it. So as you can see, there‘s room for improvement.

Spring Data repository support

Before we start refactoring the implementation, note that the sample project contains test cases that can be run in the course of the refactoring to verify the code still works. Let's now see how we can improve the implementation.

Spring Data JPA provides a repository programming model that starts with an interface per managed domain object:

public interface AccountRepository extends JpaRepository<Account, Long> {  }

Defining this interface serves two purposes: First, by extending JpaRepository we get a bunch of generic CRUD methods into our type that allows saving Accounts, deleting them and so on. Second, this will allow the Spring Data JPA repository infrastructure to scan the classpath for this interface and create a Spring bean for it.

To have Spring create a bean that implements this interface, all you need to do is use the Spring JPA namespace and activate the repository support using the appropriate element:

<jpa:repositories base-package="com.acme.repositories" />

This scans all packages below com.acme.repositories for interfaces extendingJpaRepository and creates a Spring bean for it that is backed by an implementation ofSimpleJpaRepository. Let's take a first step and refactor our AccountServiceimplementation a little bit to use our newly introduced repository interface:

@Repository
@Transactional(readOnly = true)
class AccountServiceImpl implements AccountService {

  @PersistenceContext
  private EntityManager em;

  @Autowired
  private AccountRepository repository;

  @Override
  @Transactional
  public Account save(Account account) {
    return repository.save(account);
  }

  @Override
  public List<Account> findByCustomer(Customer customer) {

    TypedQuery query = em.createQuery("select a from Account a where a.customer = ?1", Account.class);
    query.setParameter(1, customer);

    return query.getResultList();
  }
}

After this refactoring, we simply delegate the call to save(…) to the repository. By default the repository implementation will consider an entity new if its id-property is null just like you saw in the previous example (note, you can can gain more detailed control over that decision if necessary). Additionally, we can get rid of the @Transactional annotation for the method as the CRUD methods of the Spring Data JPA repository implementation are already annotated with @Transactional.

Next we will refactor the query method. Let’s follow the same delegating strategy for the query method as with the save method. We introduce a query method on the repository interface and have our original method delegate to that newly introduced method:

@Transactional(readOnly = true) 
public interface AccountRepository extends JpaRepository<Account, Long> {

  List<Account> findByCustomer(Customer customer); 
}
@Repository
@Transactional(readOnly = true)
class AccountServiceImpl implements AccountService {

  @Autowired
  private AccountRepository repository;

  @Override
  @Transactional
  public Account save(Account account) {
    return repository.save(account);
  }

  @Override
  public List<Account> findByCustomer(Customer customer) {
    return repository.findByCustomer(Customer customer);
  }
}

Let me add a quick note on the transaction handling here. In this very simple case we could remove the @Transactional annotations from the AccountServiceImpl class entirely as the repository's CRUD methods are transactional and the query method is marked with@Transactional(readOnly = true) at the repository interface already. The current setup, with methods at the service level marked as transactional (even if not needed for this case), is best because it is explicitly clear when looking at the service level that operations are happening in a transaction. Beyond that, if a service layer method was modified to do multiple calls to repository methods all the code would still execute inside a single transaction as the repository's inner transactions would simply join the outer one started at the service layer. The transactional behavior of the repositories and possibilities to tweak it are documented in detail in thereference documentation.

Try to run the test case again and see that it works. Stop, we didn't provide any implementation for findByCustomer(…) right? How does this work?

Query methods

When Spring Data JPA creates the Spring bean instance for the AccountRepository interface it inspects all query methods defined in it and derives a query for each of them. By default Spring Data JPA will automatically parses the method name and creates a query from it. The query is implemented using the JPA criteria API. In this case the findByCustomer(…) method is logically equivalent to the JPQL query select a from Account a where a.customer = ?1. The parser that analyzes the method name supports quite a large set of keywords such as AndOr,GreaterThanLessThanLikeIsNullNot and so on. You can also add OrderByclauses if you like. For a detailed overview please check out the reference documentation. This mechanism gives us a query method programming model like you're used to from Grails or Spring Roo.

Now let's suppose you want to be explicit about the query to be used. To do so you can either declare a JPA named query that follows a naming convention (in this caseAccount.findByCustomer) in an annotation on the entity or in your orm.xml. Alternatively you can annotate your repository method with @Query:

@Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {

  @Query("<JPQ statement here>")
  List<Account> findByCustomer(Customer customer); 
}

Now let's do a before/after comparison of the CustomerServiceImpl applying the features that we've seen so far:

@Repository
@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {

  @PersistenceContext
  private EntityManager em;

  @Override
  public Customer findById(Long id) {
    return em.find(Customer.class, id);
  }

  @Override
  public List<Customer> findAll() {
    return em.createQuery("select c from Customer c", Customer.class).getResultList();
  }

  @Override
  public List<Customer> findAll(int page, int pageSize) {

    TypedQuery query = em.createQuery("select c from Customer c", Customer.class);

    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);

    return query.getResultList();
  }

  @Override
  @Transactional
  public Customer save(Customer customer) {

    // Is new?
    if (customer.getId() == null) {
      em.persist(customer);
      return customer;
    } else {
      return em.merge(customer);
    }
  }

  @Override
  public List<Customer> findByLastname(String lastname, int page, int pageSize) {

    TypedQuery query = em.createQuery("select c from Customer c where c.lastname = ?1", Customer.class);

    query.setParameter(1, lastname);
    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);

    return query.getResultList();
  }
}

Okay, let's create the CustomerRepository and eliminate the CRUD methods first:

@Transactional(readOnly = true)
public interface CustomerRepository extends JpaRepository<Customer, Long> {  }
@Repository
@Transactional(readOnly = true)
public class CustomerServiceImpl implements CustomerService {

  @PersistenceContext
  private EntityManager em;

  @Autowired
  private CustomerRepository repository;

  @Override
  public Customer findById(Long id) {
    return repository.findById(id);
  }

  @Override
  public List<Customer> findAll() {
    return repository.findAll();
  }

  @Override
  public List<Customer> findAll(int page, int pageSize) {

    TypedQuery query = em.createQuery("select c from Customer c", Customer.class);

    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);

    return query.getResultList();
  }

  @Override
  @Transactional
  public Customer save(Customer customer) {
    return repository.save(customer);
  }

  @Override
  public List<Customer> findByLastname(String lastname, int page, int pageSize) {

    TypedQuery query = em.createQuery("select c from Customer c where c.lastname = ?1", Customer.class);

    query.setParameter(1, lastname);
    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);

    return query.getResultList();
  }
}

So far so good. What is left right now are two methods that deal with a common scenario: you don't want to access all entities of a given query but rather only a page of them (e.g. page 1 by a page size of 10). Right now this is addressed with two integers that limit the query appropriately. There are two issues with this. Both integers together actually represent a concept, which is not made explicit here. Beyond that we return a simple List so we lose metadata information about the actual page of data: is it the first page? Is it the last one? How many pages are there in total? Spring Data provides an abstraction consisting of two interfaces: Pageable (to capture pagination request information) as well as Page (to capture the result as well as meta-information). So let's try to add findByLastname(…) to the repository interface and rewritefindAll(…) and findByLastname(…) as follows:

@Transactional(readOnly = true) 
public interface CustomerRepository extends JpaRepository<Customer, Long> {

  Page<Customer> findByLastname(String lastname, Pageable pageable); 
}
@Override 
public Page<Customer> findAll(Pageable pageable) {
  return repository.findAll(pageable);
}

@Override
public Page<Customer> findByLastname(String lastname, Pageable pageable) {
  return repository.findByLastname(lastname, pageable); 
}

Make sure you adapt the test cases according to the signature changes but then they should run fine. There are two things this boils down to here: we have CRUD methods supporting pagination and the query execution mechanism is aware of Pageable parameters as well. At this stage our wrapping classes actually become obsolete as a client could have used our repository interfaces directly. We got rid of the entire implementation code.

Summary

In the course of this blog post we have reduced the amount of code to be written for repositories to two interfaces with 3 methods and a single line of XML:

@Transactional(readOnly = true) 
public interface CustomerRepository extends JpaRepository<Customer, Long> {

    Page<Customer> findByLastname(String lastname, Pageable pageable); 
}
@Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {

    List<Account> findByCustomer(Customer customer); 
}
<jpa:repositories base-package="com.acme.repositories" />

We have type safe CRUD methods, query execution and pagination built right in. The cool thing is that this is not only working for JPA based repositories but also for non-relational databases. The first non-relational database to support this approach will be MongoDB as part of the Spring Data Document release in a few days. You will get the exact same features for Mongo DB and we're working on support for other data bases as well.. There are also additional features to be explored (e.g. entity auditing, integration of custom data access code) which we will walk through in upcoming blog posts.



source - http://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/










Posted by linuxism
,



 DecodingExamples  
Examples of JSON decoding
Updated Aug 10, 2013 by jon.cham...@gmail.com

Example 1 - Convenient way: Use JSONValue

  System.out.println("=======decode=======");
               
 
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
 
Object obj=JSONValue.parse(s);
 
JSONArray array=(JSONArray)obj;
 
System.out.println("======the 2nd element of array======");
 
System.out.println(array.get(1));
 
System.out.println();
               
 
JSONObject obj2=(JSONObject)array.get(1);
 
System.out.println("======field \"1\"==========");
 
System.out.println(obj2.get("1"));    

               
  s
="{}";
  obj
=JSONValue.parse(s);
 
System.out.println(obj);
               
  s
="[5,]";
  obj
=JSONValue.parse(s);
 
System.out.println(obj);
               
  s
="[5,,2]";
  obj
=JSONValue.parse(s);
 
System.out.println(obj);

JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List. Please referMapping Between JSON and Java Entities for more information on entity mapping while parsing.

Example 2 - Faster way: Reuse instance of JSONParser

  JSONParser parser=new JSONParser();

 
System.out.println("=======decode=======");
               
 
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
 
Object obj=parser.parse(s);
 
JSONArray array=(JSONArray)obj;
 
System.out.println("======the 2nd element of array======");
 
System.out.println(array.get(1));
 
System.out.println();
               
 
JSONObject obj2=(JSONObject)array.get(1);
 
System.out.println("======field \"1\"==========");
 
System.out.println(obj2.get("1"));    

               
  s
="{}";
  obj
=parser.parse(s);
 
System.out.println(obj);
               
  s
="[5,]";
  obj
=parser.parse(s);
 
System.out.println(obj);
               
  s
="[5,,2]";
  obj
=parser.parse(s);
 
System.out.println(obj);

JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List. Please referMapping Between JSON and Java Entities for more information on entity mapping while parsing.

Example 3 - Exception handling

  String jsonText = "[[null, 123.45, \"a\\tb c\"]}, true";
 
JSONParser parser = new JSONParser();
               
 
try{
    parser
.parse(jsonText);
 
}
 
catch(ParseException pe){
   
System.out.println("position: " + pe.getPosition());
   
System.out.println(pe);
 
}

Result:

  position: 25
 
Unexpected token RIGHT BRACE(}) at position 25.

Please refer ParseException.java for more information.

Example 4 - Container factory

You can use ContainerFactory to create containers for parsed JSON objects and JSON arrays:

  String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
 
JSONParser parser = new JSONParser();
 
ContainerFactory containerFactory = new ContainerFactory(){
   
public List creatArrayContainer() {
     
return new LinkedList();
   
}

   
public Map createObjectContainer() {
     
return new LinkedHashMap();
   
}
                       
 
};
               
 
try{
   
Map json = (Map)parser.parse(jsonText, containerFactory);
   
Iterator iter = json.entrySet().iterator();
   
System.out.println("==iterate result==");
   
while(iter.hasNext()){
     
Map.Entry entry = (Map.Entry)iter.next();
     
System.out.println(entry.getKey() + "=>" + entry.getValue());
   
}
                       
   
System.out.println("==toJSONString()==");
   
System.out.println(JSONValue.toJSONString(json));
 
}
 
catch(ParseException pe){
   
System.out.println(pe);
 
}

Result:

  ==iterate result==
  first
=>123
  second
=>[4, 5, 6]
  third
=>789
 
==toJSONString()==
 
{"first":123,"second":[4,5,6],"third":789}

If you don't specify a container factory, org.json.simple.JSONObject is used for a Map and org.json.simple.JSONArray is used for a List. Please refer Mapping Between JSON and Java Entities for more information on entity mapping while parsing.

Example 5 - Stoppable SAX-like content handler

JSON.simple introduces a simplified and stoppable SAX-like content handler to process JSON text stream. The user can pause at any point of the logical input stream, processing other logic, then resume parsing if needed, or abort parsing if he gets the desired result, without having to wait for the whole input stream to finish. Then we have a very fast parser without sacrificing the flexibility. Here's an example of finding values of any object entry that matches a desired key:

KeyFinder.java:

class KeyFinder implements ContentHandler{
 
private Object value;
 
private boolean found = false;
 
private boolean end = false;
 
private String key;
 
private String matchKey;
       
 
public void setMatchKey(String matchKey){
   
this.matchKey = matchKey;
 
}
       
 
public Object getValue(){
   
return value;
 
}
       
 
public boolean isEnd(){
   
return end;
 
}
       
 
public void setFound(boolean found){
   
this.found = found;
 
}
       
 
public boolean isFound(){
   
return found;
 
}
       
 
public void startJSON() throws ParseException, IOException {
    found
= false;
   
end = false;
 
}

 
public void endJSON() throws ParseException, IOException {
   
end = true;
 
}

 
public boolean primitive(Object value) throws ParseException, IOException {
   
if(key != null){
     
if(key.equals(matchKey)){
        found
= true;
       
this.value = value;
        key
= null;
       
return false;
     
}
   
}
   
return true;
 
}

 
public boolean startArray() throws ParseException, IOException {
   
return true;
 
}

       
 
public boolean startObject() throws ParseException, IOException {
   
return true;
 
}

 
public boolean startObjectEntry(String key) throws ParseException, IOException {
   
this.key = key;
   
return true;
 
}
       
 
public boolean endArray() throws ParseException, IOException {
   
return false;
 
}

 
public boolean endObject() throws ParseException, IOException {
   
return true;
 
}

 
public boolean endObjectEntry() throws ParseException, IOException {
   
return true;
 
}
}

Main logic:

  String jsonText = "{\"first\": 123, \"second\": [{\"k1\":{\"id\":\"id1\"}}, 4, 5, 6, {\"id\": 123}], \"third\": 789, \"id\": null}";
 
JSONParser parser = new JSONParser();
 
KeyFinder finder = new KeyFinder();
  finder
.setMatchKey("id");
 
try{
   
while(!finder.isEnd()){
      parser
.parse(jsonText, finder, true);
     
if(finder.isFound()){
        finder
.setFound(false);
       
System.out.println("found id:");
       
System.out.println(finder.getValue());
     
}
   
}          
 
}
 
catch(ParseException pe){
    pe
.printStackTrace();
 
}

Result:

  found id:
  id1
  found id
:
 
123
  found id
:
 
null

Please refer ContentHandler.java for more information.

Example 6 - Build whole object graph on top of SAX-like content handler

Please note that JSON.simple has provided the build in functionality to do the same work. Please refer above examples for more information. Here is just an example to show how to use the SAX-like interface in a slightly more complex scenario.

Transformer.java:

class Transformer implements ContentHandler{
       
private Stack valueStack;
       
       
public Object getResult(){
           
if(valueStack == null || valueStack.size() == 0)
               
return null;
           
return valueStack.peek();
       
}
       
       
public boolean endArray () throws ParseException, IOException {
            trackBack
();
           
return true;
       
}

       
public void endJSON () throws ParseException, IOException {}

       
public boolean endObject () throws ParseException, IOException {
            trackBack
();
           
return true;
       
}

       
public boolean endObjectEntry () throws ParseException, IOException {
           
Object value = valueStack.pop();
           
Object key = valueStack.pop();
           
Map parent = (Map)valueStack.peek();
            parent
.put(key, value);
           
return true;
       
}

       
private void trackBack(){
           
if(valueStack.size() > 1){
               
Object value = valueStack.pop();
               
Object prev = valueStack.peek();
               
if(prev instanceof String){
                    valueStack
.push(value);
               
}
           
}
       
}
       
       
private void consumeValue(Object value){
           
if(valueStack.size() == 0)
                valueStack
.push(value);
           
else{
               
Object prev = valueStack.peek();
               
if(prev instanceof List){
                   
List array = (List)prev;
                    array
.add(value);
               
}
               
else{
                    valueStack
.push(value);
               
}
           
}
       
}
       
       
public boolean primitive (Object value) throws ParseException, IOException {
            consumeValue
(value);
           
return true;
       
}

       
public boolean startArray () throws ParseException, IOException {
           
List array = new JSONArray();
            consumeValue
(array);
            valueStack
.push(array);
           
return true;
       
}

       
public void startJSON () throws ParseException, IOException {
            valueStack
= new Stack();
       
}

       
public boolean startObject () throws ParseException, IOException {
           
Map object = new JSONObject();
            consumeValue
(object);
            valueStack
.push(object);
           
return true;
       
}

       
public boolean startObjectEntry (String key) throws ParseException, IOException {
            valueStack
.push(key);
           
return true;
       
}
       
   
}

Main logic:

    String jsonString = <Input JSON text>;
   
Object value = null;
   
JSONParser parser = new JSONParser();
   
Transformer transformer = new Transformer();
       
    parser
.parse(jsonString, transformer);
    value
= transformer.getResult();

The result is similar to one return from the following code:

    String jsonString = <Input JSON text>;
   
Object value = null;
   
JSONParser parser = new JSONParser();
    value
= parser.parse(jsonString);

Notes - Multithreading and extensions

JSONParser is NOT thread-safe. And please note that JSON string such as [5,,,2] is accepted by the parser and is treated as [5,2]. This doesn't violate the JSON specification, and it increases the error toleration of the input data. Some JSON grammar checker may need a 'strict' mode. Considering adding this feature.

Since it's a bit controversial on the extension of the parser (see comments of this wiki page), I'd like to make some clarifications on this topic here.

Some users may concern about exchanging important data, say medical information or financial data, between applications. I think you need to make sure the following things in such scenarios:

  1. You need to make sure you are using a reliable and full compliant encoder on the side of the source;
  2. Or if you also accept data from a non-trusted source, even a 'strict' decoder is inadequate. You may need extra validation rules to verify the source. For example, a user may send totally compliant [5,2] even though you expect [5,0,2].

In both cases, a liberal parser will do nothing harmful to your application.

The reason of accepting something like [5,,2] is that:

  1. A careless user or an encoder may repeat a comma (such as by pressing the key too long :-), which is harmless;
  2. The comma is actually redundant syntactically, if two adjacent entities are recognized.

I know some users may be FUD in front of a liberal parser, but as I mentioned above, it's harmless and is allowed in RFC4627 (actually the author of RFC4627 adopts this feature in the reference implementation).

Please feel free to leave a comment or post in the discussion group if you have further concerns. Thanks.

Comment by tsaloranta@gmail.comJan 7, 2009

Actually, why wouldn't such a non-standard feature violate JSON specification? Such a construct does not conform to the JSON syntax, so by definition it seems to explicitly violate it. And the main problem is that accepting such invalid input reduces interoperability -- other parser will not accept such structures, and it may make users less likely to use json.simple, because its behavior differs from standard behavior.

Comment by project member fangyid...@gmail.comJan 7, 2009

RFC 4627 states:

4. Parsers
A JSON parser transforms a JSON text into another representation. A JSON parser MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions.
Comment by project member fangyid...@gmail.comJan 10, 2009

It does not cause interoperability issues because the encoding is always right, and JSON.simple always accepts inputs that conform to the JSON grammar.

Comment by project member fangyid...@gmail.comJan 12, 2009

Actually, JSON.org's RI goes further on extension. It accepts single quote strings and hex number: ['total' : 0x20].

Comment by tsaloranta@gmail.comFeb 9, 2009

Yes, RI is non-compliant as well. It is true that specification allows for extensions; unfortunately there are no commonly defined "common" extensions and thus each parser seems to adopt their own favorite hacks.

But it is bit naive to think that accepting non-valid input would not lead to interoperability problems -- this is EXACTLY how browsers degenerated into accepting all kinds of broken html. So personally I think it is wrong to add short-cuts for what are essentially broken documents (missing values, or extra commas).

But it is your parser of course, and you can add any extensions that you like. :-)

Comment by project member fangyid...@gmail.comFeb 10, 2009

Please read RFC4627 carefully, then you'll find the lines as below:

5. Generators

   A JSON generator produces JSON text
.  The resulting text MUST
   strictly conform to the JSON grammar
.

That is, the encoder should be always right, so the interoperability problem will never happen. The extension of the parser is to increase the robustness of the application. Both the RI and JSON.simple are fully compliant with RFC4627. If you insists that there will be interoperability problems, it's the problem of the specification, not the library. But the fact is, it will never happen.

Comment by arnauldvmMar 13, 2009

I agree with tsaloranta.

Accepting non-compliant input creates the risk of letting non-compliant content spread (e.g. contents generated by hand, or by another system that has a flaw). As long as the only "client" to these contents is read by a "tolerant" parser you have no problem.

The day another system, using a more strict parser, comes into play, you have your interoperability problem, and it might be too late to come back.

Comment by PeterQui...@gmail.comMar 15, 2009

arnauldvm, tsaloranta: Please take the time to review Postel's Law: "Be conservative in what you do; be liberal in what you accept from others."

http://en.wikipedia.org/wiki/Postel%27s_law

The responsibility for enforcing valid JSON lies with the encoder, not the decoder. The decoder's sole responsibility is to parse JSON. By gracefully accepting invalid input, the decoder becomes more robust and usable.

Comment by keithdwi...@gmail.comMar 18, 2009

"Be conservative in what you do; be liberal in what you accept from others."

The complication lies in that "accepting" means making assumptions about the intention of the author. Does "5,,,2" mean "5,2", or "5,null,null,2", "5,0,0,2", or something else?

I suspect that if I were parsing, say, important medical data, I would need a strict mode, that would fail in this case, or at least warn somehow.

Comment by project member fangyid...@gmail.comMar 18, 2009

Hi keithdwinkler, if you are exchanging important data, say medical information or financial data, between applications, I think you need to make sure the following things in such scenarios:

  1. You need to make sure you are using a reliable and full compliant encoder on the side of the source;
  2. Or if you also accept data from a non-trusted source, even a 'strict' decoder is inadequate. You may need extra validation rules to verify the source. For example, a user may send totally compliant [5,2] even though you expect [5,0,2].

In both cases, a liberal parser will do nothing harmful to your application.

The reason of accepting something like [5,,2] is that:

  1. A careless user or an encoder may repeat a comma (such as by pressing the key too long :-), which is harmless;
  2. The comma is actually redundant syntactically, if two adjacent entities are recognized.

I know some users may be FUD in front of a liberal parser, but as I mentioned above, it's harmless and is allowed in RFC4627 (actually the author of RFC4627 adopts this feature in the reference implementation).

Please feel free to leave a comment or post in the discussion group if you have further concerns. Thanks.

Comment by eliseos...@gmail.comNov 3, 2009

Any particular reason why JSONValue.parse(s) returns an Object and not a more proper JSONObject?

Comment by project member fangyid...@gmail.comNov 3, 2009

Because we also have a JSONArray and other primitives.

Comment by rheyw...@google.comAug 6, 2010

I have a simple, irrefutable need for a completely strict parser: I have a piece of code that produces JSON, so I need a strict parser to validate it during unit tests. I tried to use JSONObject(), but of course JSONObject accepts invalid JSON, so my tests pass even though my program is incorrect.

Can someone recommend an easy-to-use, open-source Java library that throws an exception when it encounters invalid JSON?

Comment by coenw...@gmail.comSep 24, 2010

To unit test the JSON output, compare it to a static string that is the expected output. If you attempt to do anything else you are doing one or more of:

  1. Testing more than just the desired method
  2. Permitting bugs/features in other code to allow your test to pass when it should fail

Either of those is bad. The best solution is to compare the output to the expected value, which would be a string, rather than parsing it.

Comment by dean.hil...@gmail.comDec 14, 2010

please PLEASE add strict mode. The reason being is that I want to know if system A is sending input like 1,,,,5 early on so that if we have system A start sending to other systems(not just json-simple), we won't know. it is easier to start strict and move to more flexible than it is to go from flexible to strict....heck try adding checkstyle to a 3.0 project vs. adding it to a 0.1 release project...big difference on making things stricter...it's harder to go one way then the other.

I also don't like having to write tests with the "raw" data as suggested above...that is much akin to using hibernate and writing hibernate ejbs into the db and then doing raw sql because you don't trust hibernate...hibernate should already have those tests.

Comment by finbarom...@gmail.comFeb 27, 2011

Maybe this isnt exactly the place to be asking questions, but im new to java and im having an issue with the container class example I literally copied and pasted the code into my class to attempt to decode the following which was passed back from the server side {"uid":2,"name":"john"}{"uid":3,"name":"mary"} so essentially (int,string) I believe the error is from the line return new LinkedHashMap?(); and the error is Unexpected token LEFT BRACE({) at position 23.

Any help would be appreciated Regards

Comment by spelud...@gmail.comMar 16, 2011

@finbar, your JSON represents two objects. The code works with just one, ie {"uid":2,"name":"john"}. The error message is the parser complaining about the left brace at the start of the second object (ie 23 characters in).

Since the server sent separate JSON strings (it didn't return an array?), then you could call the example piece of code once for each individual string.

Comment by shilpi.m...@gmail.comJul 13, 2011

How can we disable the display of JSON value in "View Source" of a browser?

Comment by drver...@gmail.comSep 20, 2011

I noticed a critical error in the JSON Maps mentioned in the below code: Map json = (Map)parser.parse(jsonText, containerFactory);

Iterator iter = json.entrySet().iterator(); System.out.println("==iterate result=="); while(iter.hasNext()){
Map.Entry entry = (Map.Entry)iter.next(); System.out.println(entry.getKey() + "=>" + entry.getValue());
}
Object obj=JSONValue.parse(json2.get("items").toString()); JSONArray array=(JSONArray)obj;

There one of the key item is an array that has some strings, but it is failing to parse that array list, because it is removing all the quotes """ from the key values, so we cannot process it further as arrays, I think its a major flaw.

Comment by paul.reb...@gmail.comOct 13, 2011

I tried to reproduce your major flaw but I'm not sure if you provided all the information needed.

  • where does the object "json2" come from? I renamed to "json"
  • the get method on that object tries to retrieve the value which is stored under the key "items", which doesn't exist and throws a NullPointerException??. I suppose you tried to get a list of the array items instead, correct? In that case you need another approach.
Comment by vis...@voicetap.inNov 18, 2011

Dear,

I have following json responce. I am not able to iterate through each Map. Please help me

{"status":"OK","result":{"1":{"Id":"3","Conferencce":"test3","Description":"test3","Admin":"919818559890","Moderator":null,"Keywords":"test3","StartDate?":"2011-11-19 12:22:33","EndDate?":"2011-11-19 14:22:33","Type":"both","MaxAtendee?":"0","MinAtendee?":"0","RegAtendee?":"0","DescVoiceVideo?":null,"Rating":null,"Status":"active","ApproveBy?":null,"ApprovedOn?":"2011-11-15 14:22:33","ApprovedReason?":null,"AdminPin?":null,"UserPin?":null,"PricePerMin?":null,"PricePerConf?":null,"ReminderStart?":null,"AdminJoin?":null,"CreatedOn?":"2011-11-17 13:31:27","CreatedBy?":"1"},"2":{"Id":"2","Conferencce":"test2","Description":"test","Admin":"919818559899","Moderator":null,"Keywords":"test2","StartDate?":"2011-11-18 12:22:33","EndDate?":"2011-11-18 14:22:33","Type":"both","MaxAtendee?":"0","MinAtendee?":"0","RegAtendee?":"0","DescVoiceVideo?":null,"Rating":null,"Status":"active","ApproveBy?":null,"ApprovedOn?":"2011-11-15 12:22:33","ApprovedReason?":null,"AdminPin?":null,"UserPin?":null,"PricePerMin?":null,"PricePerConf?":null,"ReminderStart?":null,"AdminJoin?":null,"CreatedOn?":"2011-11-17 13:31:20","CreatedBy?":"1"},"3":{"Id":"1","Conferencce":"test","Description":"tes","Admin":"919818559898","Moderator":null,"Keywords":"test","StartDate?":"2011-11-17 12:22:33","EndDate?":"2011-11-17 14:22:33","Type":"both","MaxAtendee?":"0","MinAtendee?":"0","RegAtendee?":"0","DescVoiceVideo?":null,"Rating":null,"Status":"active","ApproveBy?":"1","ApprovedOn?":"2011-11-15 12:22:33","ApprovedReason?":null,"AdminPin?":null,"UserPin?":null,"PricePerMin?":null,"PricePerConf?":null,"ReminderStart?":null,"AdminJoin?":null,"CreatedOn?":"2011-11-17 13:31:15","CreatedBy?":"1"}}}

Comment by bentai...@gmail.comFeb 12, 2012

How can I marshal this "device" object using ContainerFactory??

{

"myDevicesInfo": [
{
"DeviceType?":"foo", "DeviceName?":"foo1", "IPAddress":"192.168.1.1", "UserName?":"admin", "Password":"pw"
}
]
}

Comment by cin...@gmail.comMay 18, 2012

I have a input stream (bound to a socket), that continuously gives multiple JSON docs, and I want to parse it one by one. If i use json-simple, it will stop at the beginning of the second JSON doc ('{') with an exception.

How can I parse multiple JSON docs in one stream??

Comment by vantaiit@gmail.comOct 17, 2012

[{"name":"1350458288_11294.jpg","size":775702,"type":"image\/jpeg","url":"http:\/\/localhost\/oto\/files\/1350458288_11294.jpg","thumbnail_url":"http:\/\/localhost\/oto\/thumbnails\/1350458288_11294.jpg","delete_url":"http:\/\/localhost\/oto\/?file=1350458288_11294.jpg","delete_type":"DELETE"}]

whats is Json ?

Comment by aand...@gmail.comNov 9, 2012

Hi, i have a question about reading json file. In file I have several lines. Each line with {}. How can i parse some data from each line in a loop? Thanks a lot!!

Comment by pas...@gmail.comApr 23, 2013

I just added this class util to my project:

import org.json.simple.JSONObject;

public class JSONObjectUtil {

public static String retrieveJsonPath (JSONObject json, String path){

if (!path.contains("/")) {
return json.get(path).toString();
} else {
String paths = path.split("/"); JSONObject newJson = (JSONObject) json.get(paths0?); String newPath = path.substring(path.indexOf("/") + 1); return retrieveJsonPath(newJson, newPath);
}
}
}

In this way, retrieving a value from a JSONObject is pretty simple:

JSONObjectUtil.retrieveJsonPath(json, "glossary/GlossDiv?/GlossList?/GlossEntry?/SortAs?")

Comment by simona.u...@gmail.comMay 15, 2013

A lot of people are asking for recursive iteration. This is my solution.

A class with static print methods for printing and navigating through Map and List objects.

public class MyStaticClass {

       
public static void print(Map m){
               
Iterator iterator = m.entrySet().iterator();
           
print(iterator);
       
}
       
       
public static void print(List l){
               
Iterator iterator = l.iterator();
           
while (iterator.hasNext()){
               
System.out.println(iterator.next());
           
}
       
}
       
       
public static void printRecursive(Object o){
               
if (o == null)
                       
return;
               
               
if (o instanceof java.util.LinkedList)
                        printRecursive
((List) o);
               
               
if (o instanceof java.util.HashMap)
                        printRecursive
((Map) o);
               
       
}
       
       
private static void printRecursive(Map map){
               
if (map == null)
                       
return;
               
               
if (map.size() > 0){
                       
print(map);
                       
                       
Iterator iterator = map.values().iterator();
                       
Object o = null;
                       
while(iterator.hasNext()){
                                o
= iterator.next();
                               
if ((o instanceof java.util.HashMap) || (o instanceof java.util.LinkedList))
                                        printRecursive
(o);
                       
}
               
}
       
}
       
       
private static void printRecursive(List list){
               
if (list == null)
                       
return;
               
               
if (list.size() > 0){
                       
print(list);
                       
                       
Iterator iterator = list.iterator();
                       
Object o = null;
                       
while(iterator.hasNext()){
                                o
= iterator.next();
                               
if ((o instanceof java.util.HashMap) || (o instanceof java.util.LinkedList))
                                        printRecursive
(o);
                       
}
               
}
       
}
       
       
private static void print(Iterator iter){
               
while(iter.hasNext()){
                     
Map.Entry entry = (Map.Entry)iter.next();
                     
System.out.println(entry.getKey() + " => " + entry.getValue());
                   
}
       
}
}

A ContainerFactory? returning the types I want:

public class BasicContainerFactory implements ContainerFactory {
       
       
@Override
       
public List creatArrayContainer() {
               
return new LinkedList();
       
}

       
@Override
       
public Map createObjectContainer() {
               
return new HashMap();
       
}

}

And you can call it like this:

JSONParser parser =  new JSONParser();
               
BasicContainerFactory bcfactory = new BasicContainerFactory();
               
try {
                       
Object json = parser.parse(jsonData, bcfactory);
                       
MyStaticClass.printRecursive(json);                  

               
} catch (ParseException pe){
                        pe
.printStackTrace(System.err);
               
}
Comment by periyasa...@gmail.comJul 12, 2013

Thanks for JSON recursive function. I need to manipulate(add,delete and update) my JSON string and then reform the JSON object


{
"appConfig": {
"applicationName": "UserSetp?", "appnamespace": "IES", "moduleName": "usersetup", "language": "en", "uitemplate": "simplepanel"
}, "appView": {
"xtype": "simplepanel", "extend": "IES.view.ux.template.AbstractSimplePanel?", "alias": "usersetupview", "formfields": [
{
"xtype": "form", "bodyPadding": 10, "draggable": false, "height": 200, "width": 400, "title": "My Form", "items": [
{
"xtype": "xtdtext", "fieldLabel": "Text Field1", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "draggable": false, "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "a982fdad-c623-4709-bf91-059df8e11b11", "id": "a982fdad-c623-4709-bf91-059df8e11b11", "layout": "anchor"
}, {
"xtype": "xtdtext", "fieldLabel": "Text Field2", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "draggable": false, "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "4beb37a7-d0a9-4f97-a539-2da286086052", "id": "4beb37a7-d0a9-4f97-a539-2da286086052", "layout": "anchor"
}, {
"xtype": "xtdfieldset", "draggable": false, "ddGroup": "DesignerGroup?", "title": "My Fields3", "height": 200, "width": 400, "items": [
{
"xtype": "xtddatefield", "draggable": false, "fieldLabel": "MyDate4?", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "434c101a-2bd6-4c73-a5f6-07bb59ceb361", "id": "434c101a-2bd6-4c73-a5f6-07bb59ceb361", "labelSeparator": " ", "anchor": "100%", "layout": "anchor"
}, {
"xtype": "xtdcombobox", "fieldLabel": "My combobox5", "queryMode": "local", "draggable": false, "labelAlign": "left", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "85aae1d9-8b3b-4bc8-95f3-ff9175451219", "id": "85aae1d9-8b3b-4bc8-95f3-ff9175451219", "labelSeparator": " ", "anchor": "100%", "layout": "anchor"
}
], "resizable": {
"dynamic": true, "handles": "all"
}, "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "cafa5ffd-eb55-4208-8fb3-2e3aafbbe436", "id": "cafa5ffd-eb55-4208-8fb3-2e3aafbbe436", "layout": "anchor"
}, {
"xtype": "panel", "title": "My Panel6", "width": 400, "height": 400, "items": [
{
"xtype": "xtdcombobox", "fieldLabel": "My combobox7", "queryMode": "local", "draggable": false, "labelAlign": "left", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "7757aba7-d111-41ae-8c7c-8709815cc5bb", "id": "7757aba7-d111-41ae-8c7c-8709815cc5bb", "layout": "anchor"
}, {
"xtype": "container", "ddGroup": "DesignerGroup?", "width": 80, "height": 30, "items": [
{
"xtype": "xtdbutton", "text": "Save", "designerId": "c8ccb53f-af4b-40d4-a8bd-411422feed11", "id": "c8ccb53f-af4b-40d4-a8bd-411422feed11"
}, {
"xtype": "xtdbutton", "text": "Clear", "designerId": "fa4d47d9-86f8-4268-888c-30b23c6279d3", "id": "fa4d47d9-86f8-4268-888c-30b23c6279d3"
}
], "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "draggable": false, "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "dc5a6405-7b87-432b-867c-efeacf1f1ccf", "id": "dc5a6405-7b87-432b-867c-efeacf1f1ccf"
}, {
"xtype": "tabpanel", "title": "MyTabPanel?", "draggable": false, "height": 200, "width": 400, "activeTab": 0, "items": [
{
"xtype": "panel", "title": "Tab 1", "items": [
{
"xtype": "xtdtext", "fieldLabel": "Text Field", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "draggable": false, "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "80907e08-ef2c-4338-93eb-9877bb869910", "id": "80907e08-ef2c-4338-93eb-9877bb869910"
}
], "designerId": "44bd0211-ed5c-4dfc-858a-88ac2a8738bb", "id": "44bd0211-ed5c-4dfc-858a-88ac2a8738bb"
}, {
"xtype": "panel", "items": [
{
"xtype": "xtdtextareafield", "draggable": false, "fieldLabel": "My TextArea?", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "2ab787ed-666a-403f-8d3f-c656b1929dbf", "id": "2ab787ed-666a-403f-8d3f-c656b1929dbf"
}
], "title": "Tab 2", "designerId": "060fb69d-585d-4bf1-9704-34ae4d1a58ac", "id": "060fb69d-585d-4bf1-9704-34ae4d1a58ac"
}, {
"xtype": "panel", "items": [
{
"xtype": "xtdnumberfield", "draggable": false, "fieldLabel": "My Number", "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "ee2f0bde-1e39-4d2c-835d-f312451bf767", "id": "ee2f0bde-1e39-4d2c-835d-f312451bf767"
}
], "title": "Tab 3", "designerId": "0f3ec5bb-4ba1-4938-9f42-d5d578814a7d", "id": "0f3ec5bb-4ba1-4938-9f42-d5d578814a7d"
}
], "resizable": {
"dynamic": true, "handles": "all"
}, "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "b69c2b7c-0696-4f1b-b576-73b6b861dc8c", "id": "b69c2b7c-0696-4f1b-b576-73b6b861dc8c"
}
], "draggable": false, "cls": "x-dd-drop-ok", "resizable": {
"dynamic": true, "handles": "all"
}, "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "463674ec-3251-4ce0-8ca0-5dcd5e86f613", "id": "463674ec-3251-4ce0-8ca0-5dcd5e86f613", "layout": "anchor"
}
], "resizable": {
"dynamic": true, "handles": "all"
}, "border": 1, "disabled": false, "disabledCls": "x-item-disabled", "editable": true, "hidden": false, "labelAlign": "left", "labelWidth": 100, "margin": 5, "maskRe": "", "msgTarget": "side", "padding": "", "readOnly": false, "tabIndex": "", "validateBlank": false, "validateOnBlur": true, "validateOnChange": true, "value": "", "designerId": "ac0e17da-277a-48eb-9c79-194c31e94a31", "id": "ac0e17da-277a-48eb-9c79-194c31e94a31"
}
]
}, "appController": {
"name": "UserSetpController?", "extend": "IES.controller.AbstractFrameworkController?", "stores": "UserSetupStore?", "models": "UserSetupModel?", "views": "UserSetupView?", "listeners": "save"
}, "appModel": {
"name": "UserSetpModel?", "alias": "usersetupmodel", "extend": "IES.store.AbstractModel?", "model": "usersetupModel"
}, "appStore": {
"name": "UserSetpStore?", "alias": "usersetupstore", "extend": "IES.store.AbstractStore?", "model": "UserSetupModel?"
}
}



source - https://code.google.com/p/json-simple/wiki/DecodingExamples




'Development > Java' 카테고리의 다른 글

java - file memory  (0) 2014.10.30
java - URLConnection, cookie, session  (0) 2014.04.17
java - local host ip address  (0) 2014.02.13
java - HttpURLConnection  (0) 2014.02.07
java - 화폐 원 단위 콤마 표시  (2) 2013.10.02
Posted by linuxism
,