java json

 

json搞的头疼,总是索不到自己想要的!

 

-------------------------------实例1-------------------------------

package com.json.java;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONObjectSample {
  //创建JSONObject对象  
    private static JSONObject createJSONObject(){  
        JSONObject jsonObject = new JSONObject();  
        jsonObject.put("name", "kevin");  
        jsonObject.put("Max.score", new Integer(100));  
        jsonObject.put("Min.score", new Integer(50));  
        jsonObject.put("nickname", "picglet");  
        return jsonObject;  
   }  
   
    public static void main(String[] args) {  
        JSONObject jsonObject = JSONObjectSample.createJSONObject();  
        //输出jsonobject对象  
        System.out.println("jsonObject==>"+jsonObject);  
          
        //判读输出对象的类型  
        boolean isArray = jsonObject.isArray();  
        boolean isEmpty = jsonObject.isEmpty();  
        boolean isNullObject = jsonObject.isNullObject();  
        System.out.println("isArray:"+isArray+" isEmpty:"+isEmpty+" isNullObject:"+isNullObject);  
          
        //添加属性  
        jsonObject.element("address", "swap lake");  
        System.out.println("添加属性后的对象==>"+jsonObject);  
          
        //返回一个JSONArray对象  
        JSONArray jsonArray = new JSONArray();  
        jsonArray.add(0, "this is a jsonArray value");  
        jsonArray.add(1,"another jsonArray value");  
        jsonObject.element("jsonArray", jsonArray);  
        JSONArray array = jsonObject.getJSONArray("jsonArray");  
        System.out.println("返回一个JSONArray对象:"+array); 
 
        //添加JSONArray后的值  
        //{"name":"kevin","Max.score":100,"Min.score":50,"nickname":"picglet","address":"swap lake",  
        //"jsonArray":["this is a jsonArray value","another jsonArray value"]}  
        System.out.println(jsonObject);  
          
        //根据key返回一个字符串  
        String jsonString = jsonObject.getString("name");  
        System.out.println("jsonString==>"+jsonString);  
    }  
}

 


 

-------------------------------实例2-------------------------------

--自己写的jsonutils

 

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.JSONUtils;

/*
 * 用于 java --> json 时日期格式的转换
 *
 *  JsonConfig jconfig = new JsonConfig();
 *  jconfig.registerJsonValueProcessor(java.util.Date.class,
 *   new DateJsonValueProcessor());
 *
 * json --> java 时日期格式的转换设置
 *
 *   String[] dateFormats = new String[] {"yyyy-MM-dd hh:mm:ss"};  
 *   JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
 */

public class DateJsonValueProcessor implements JsonValueProcessor {
 
 public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
 private SimpleDateFormat sdf;
 
 public DateJsonValueProcessor() {  
  JSONUtils.getMorpherRegistry().registerMorpher(
    new DateMorpher(new String[] {DEFAULT_DATE_PATTERN}));
  sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
 }
 
 public DateJsonValueProcessor(String datePattern) {
  try {
   JSONUtils.getMorpherRegistry().registerMorpher(
     new DateMorpher(new String[] {datePattern}));
   sdf = new SimpleDateFormat(datePattern);
  } catch(RuntimeException e) {
   sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
  }
 }
 
 public Object processArrayValue(Object value, JsonConfig cfg) {
  return process(value);
 }

 public Object processObjectValue(String key, Object value, JsonConfig cfg) {
  return process(value);
 }
 
 private Object process(Object value) {
  if(value == null) {
   return "";
  }
  if(value instanceof Date) {
   return sdf.format(value);
  }
  return value.toString();
 }
}

 

 

 

import java.util.ArrayList;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

public class JsonUtils {

 public static JsonConfig getJsonConfig() { 
  JsonConfig cfg = new JsonConfig();
  cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
  return cfg;
 }
 
 public static JsonConfig getJsonConfig(String datePattern) {
  JsonConfig cfg = new JsonConfig();
  cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(datePattern));
  return cfg;
 }
 
 public static Object toBean(JSONObject jsonObject, Class<? extends Object> rootClass) {
  JsonConfig cfg = getJsonConfig();
  cfg.setRootClass(rootClass);
  return JSONObject.toBean(jsonObject,cfg);
 }
 
 public static Object toBean(JSONObject jsonObject, Class<? extends Object> rootClass, JsonConfig cfg) {
  cfg.setRootClass(rootClass);
  return JSONObject.toBean(jsonObject,cfg);
 }
 
 public static JSONObject toJsonObject(Object bean) {
  JsonConfig cfg = getJsonConfig();
  return JSONObject.fromObject(bean, cfg);
 }
 
 public static JSONArray toJsonArray(Object list) {
  JsonConfig cfg = getJsonConfig();
  return JSONArray.fromObject(list, cfg);
 }
 
 public static JSONArray toJsonArray(Object list, JsonConfig cfg) {
  return JSONArray.fromObject(list, cfg);
 }
 
 @SuppressWarnings("unchecked")
 public static ArrayList<? extends Object> toList(JSONArray jsonArray, Class<? extends Object> rootClass) {
  
  JsonConfig cfg = getJsonConfig();
  cfg.setRootClass(rootClass);
  return  (ArrayList<? extends Object>) JSONArray.toCollection(jsonArray,cfg);
 }
}

 

 

public class Card {
 private Integer id;
 private String cardNo;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getCardNo() {
  return cardNo;
 }
 public void setCardNo(String cardNo) {
  this.cardNo = cardNo;
 }
}

 

 

public class Friend {
 private String name;
 private Integer age;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
}

 

 

import java.util.Date;
import java.util.ArrayList;
import java.util.List;
public class Student {

 private Integer id;
 private String name;
 private Date birthday;
 
 private Card card = new Card();
 private List<Friend> friends = new ArrayList<Friend>();
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
 public Card getCard() {
  return card;
 }
 public void setCard(Card card) {
  this.card = card;
 }
 public List<Friend> getFriends() {
  return friends;
 }
 public void setFriends(List<Friend> friends) {
  this.friends = friends;
 }
}

 

 

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

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonStringTest {
 public static void main(String[] args) {
  Student student = new Student();
  student.setId(1);
  student.setName("shabao");
  student.setBirthday(new Date());
   Card card = new Card();
   card.setId(1);
   card.setCardNo("0020220");
  student.setCard(card);
   List<Friend> friends = new ArrayList<Friend>();
   for (int i = 1; i < 3; i++) {
    Friend friend = new Friend();
    friend.setName("maoming"+i);
    friend.setAge(19+i);
    friends.add(friend);
   }
  student.setFriends(friends);
  
  // It will Javabean convert to String
  String jsonStudent = JsonUtils.toJsonObject(student).toString();
  System.err.println(jsonStudent);
  
  // It will String convert to Javabean
  Map<String, Object> map = new HashMap<String, Object>();  //String-->Property ; Object-->Clss
  map.put("card", Card.class);
  map.put("friends", Friend.class);
  JsonConfig config = JsonUtils.getJsonConfig();
  config.setClassMap(map);
  Student stu = (Student) JsonUtils.toBean(JSONObject
    .fromObject(jsonStudent), Student.class, config);
  
  System.err.println(stu.getBirthday());
  Card car = stu.getCard();
  System.err.println(car.getCardNo());
  List<Friend> frilist = (ArrayList<Friend>)stu.getFriends();
  for (Friend friend : frilist) {
   System.err.println(friend.getName());
  }
 }
}

 

 

 

--------- 这种情况传的参数是几个String,并不是某个对象的属性

-------------------- Flex 端 对象转 String(jsonString) -----------------

var objParams1:Object = {"brNameStrFor":"saboo", "brNo":null, "brNameChi":"沙暴"};
var jsonobj1:String = JsonUtils.encode(objParams1);  trace("ModuleProxy.findContractorListByCondition1  arrayParams : " + jsonobj1);   
ws.send(jsonobj1) 

 

   var arrayParams:Array = new Array({"brNameStrFor":"saboo", "brNo":null, "brNameChi":"沙暴"});
   var jsonarray:String = JsonUtils.encode(arrayParams);
   trace("arrayParams : " + arrayParams);
   
   var arrayParams1:Array = new Array([{"brNameStrFor":"saboo", "brNo":null, "brNameChi":"沙暴"}]);
   var jsonarray1:String = JsonUtils.encode(arrayParams1);
   trace("arrayParams : " + jsonarray1);
   
   var objParams:Object = new Object();

   objParams.brNameStrFor = brNameStrFor;
   objParams.brNo = c.brNo;
   objParams.brNameChi = c.brNameChi;
   var jsonobj:String = JsonUtils.encode(objParams);
   trace("arrayParams : " + jsonobj);

 

-------------------- java 端 String(jsonString) 转 对象 并取得相应的值  -----------------

System.out.println(jsonString); // String jsonString = "{\"brNameStrFor\":\"saboo\", \"brNo\":null, \"brNameChi\":\"沙暴\"}";

 JSONObject jsonObject = JSONObject.fromObject(jsonString);
   String brName  = jsonObject.getString("brNameStrFor").toString();
   Integer brNo = jsonObject.getString("brNo").equals("null")?null:Integer.parseInt(jsonObject.getString("brNo").toString());
   String brNameChi = jsonObject.getString("brNameChi").toString();

 

 

--------- 传某个对象的属性

-- 这个比较简单 有时间写

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