日期:2014-05-20  浏览次数:20661 次

java 获取JSONObject中“键”与“值”
今天刚写的原创代码。在网上找了好久没找到,可以从JSON中解析到key的方法。于是自己动手写了一个方法。

/**
 * 将json键值对分别解析到数组中
 * 
 * @param jsonject
 *            需要解析的json对象
 * @param type
 *            决定返回值的内容:键或值
 * @return type="key":返回json对象中"键"的字符串, type="key""value":返回json对象中"值"的字符串
 */
private String[] analyzeJsonToArray(JSONObject jsonject, String type) {

String string = jsonject.toString();
string = string.replace("}", "");
string = string.replace("{", "");
string = string.replace("\"", "");
String[] strings = string.split(",");

if (type.equals("key")) {
String[] stringsNum = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
stringsNum[i] = strings[i].split(":")[0];
}
return stringsNum;
} else if (type.equals("value")) {
String[] stringsName = new String[strings.length];
for (int i = 0; i < strings.length; i++) {
stringsName[i] = strings[i].split(":")[1];
}
return stringsName;
} else {
return null;
}
}
原创 解析JSON java

------解决方案--------------------
输出:
1
2
3
4
5
6
7
8
9
10
11
12
13

------解决方案--------------------
看哥这个狗成熟不  公司用好几年了 。
package com.cmmb.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
  
  public static String encodeList(Object[] objs) {
    return encodeList(Arrays.asList(objs));
  }

  @SuppressWarnings("unchecked")
  public static String encodeList(Collection objs) {
    JSONArray list = new JSONArray();
    if (objs == null 
------解决方案--------------------
 objs.size() == 0)
      return list.toString();
    for (Object ae : objs) {
      list.add(ae);
    }
    return list.toString();
  }
  
  @SuppressWarnings("unchecked")
  public static String encodeObject(Object obj){
    if(obj instanceof Collection)
      return encodeList((Collection)obj);
    JSONObject jo = JSONObject.fromObject(obj);
    return jo.toString();
  }
  
  @SuppressWarnings("unchecked")
  public static <T>List<T> decodeList(String str, Class<T> clazz) {
    if (str == null 
------解决方案--------------------
 "".equals(str))
      return null;
    JSONArray obj = JSONArray.fromObject(str);
    Object[] rts = obj.toArray();
    List<T> result = new ArrayList<T>(rts.length);
    for (int i = 0; i < rts.length; i++) {
      Object jo = rts[i];
      T ele = (T)JSONObject.toBean((JSONObject) jo, clazz);
      result.add( ele );
    }
    return result;
  }
  
  @SuppressWarnings("unchecked")
  public static <T>T decodeObject(String json,Class<T> clz){
    JSONObject jsonObject = JSONObject.fromObject(json);
    T bean = (T) JSONObject.toBean(jsonObject, clz);
    return bean;
  }
}