借助JSON,对象,JSON对象和字符串之间互相转化

package com.joe.test.json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;

/**
 * @author joe
 */
public class JsonTest {
    public static void main(String[] args) {
        User user1 = new User();
        user1.setUsername("username1");
        user1.setPassword("password1");
        User user2 = new User();
        user2.setUsername("username2");
        user2.setPassword("password2");
        //List
        List<User> userList = new ArrayList<User>();
        userList.add(user1);
        userList.add(user2);
        JSONArray jsonArr = JSONArray.fromObject(userList);
        String jsonString = jsonArr.toString();
        System.out.println("jsonArr=" + jsonString);
        
        JSONArray jArr = JSONArray.fromObject(jsonString);
        List<User> uList = (List<User>) JSONArray.toCollection(jArr,User.class);
        for(User u:uList){
            System.out.println("username="+u.getUsername()+",password="+u.getPassword());
        }
    }
}

你可能感兴趣的:(java,json,.net)