All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yixan.tools.common.util.KeyString Maven / Gradle / Ivy

There is a newer version: 3.7.1
Show newest version
package com.yixan.tools.common.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;

/**
 * KeyString类
 *
 * @author 赵卉华
 * @version C01 2014年5月21日
 */
public class KeyString extends KeyValue {

    /**
     * 构造函数
     */
    public KeyString() {
        super();
    }

    /**
     * 构造函数
     *
     * @param key KEY
     * @param value VALUE
     */
    public KeyString(String key, String value) {
        super(key, value);
    }

    /**
     * 将字符串转换为KeyString对象
* valueOf("{'key':1,'value':'冷水'}")
* 或: valueOf("{'1':'冷水'}")
* * @param text 字符串 * @return KeyString对象 */ public static KeyString valueOf(String text) { if (VerifyUtil.isBlank(text)) { return null; } JSONObject json = JSON.parseObject(text); return valueOf(json); } /** * 将字符串转换为KeyString对象数组
* listOf("[{'key':1,'value':'冷水'},{'key':2,'value':'热水'}]")
* 或: listOf("{'1':'冷水','2':'热水','3':'直饮水'}")
* --> List<KeyString> * * @param text 字符串 * @return List<KeyString> 对象数组 */ public static List listOf(String text) { if (VerifyUtil.isBlank(text)) { return null; } List list = new ArrayList<>(); Object object = JSON.parse(text); if (object instanceof JSONArray) { JSONArray array = (JSONArray) object; for (Object i : array) { list.add(valueOf((JSONObject) i)); } } else if (object instanceof JSONObject) { JSONObject json = (JSONObject) object; for (Map.Entry entry : json.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); String string = TypeUtils.castToJavaBean(value, String.class); list.add(new KeyString(key, string)); } } Collections.sort(list); return list; } private static KeyString valueOf(JSONObject json) { if (json.containsKey("key")) { return JSON.toJavaObject(json, KeyString.class); } else { for (Map.Entry entry : json.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); String string = TypeUtils.castToJavaBean(value, String.class); return new KeyString(key, string); } throw new IllegalArgumentException("json is empty."); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy