Sort by initial key name
JAVA
private static void sortField(Class> clazz, List fields) {
Class> parent = clazz.getSuperclass();
if (parent != null) {
sortField(parent, fields);
}
Field[] var3 = clazz.getDeclaredFields();
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
Field field = var3[var5];
fields.add(field.getName());
}
Collections.sort(fields);
}
private static void append(Object entity, List fields, StringBuilder hmacSource) throws IllegalAccessException {
Class> clazz = entity.getClass();
Iterator var4 = fields.iterator();
label95:
while(var4.hasNext()) {
String fieldName = (String)var4.next();
Field field;
try {
field = clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException var16) {
field = findParentField(entity, fieldName);
}
if (field != null && !field.isSynthetic()) {
field.setAccessible(true);
Object obj = field.get(entity);
Class> type = field.getType();
Type superType = field.getGenericType();
Class> genericClass = null;
if (superType instanceof ParameterizedType) {
Type[] genericType = ((ParameterizedType)superType).getActualTypeArguments();
genericClass = (Class)genericType[0];
}
if (type.isArray()) {
Object[] objects = (Object[])((Object[])obj);
if (objects != null && objects.length > 0) {
Object[] var22 = objects;
int var23 = objects.length;
for(int var24 = 0; var24 < var23; ++var24) {
Object object = var22[var24];
append(object, hmacSource);
}
}
} else {
Iterator it;
Object next;
if (!(obj instanceof Collection)) {
if (obj instanceof Map) {
Map map = (Map)obj;
it = map.keySet().iterator();
while(it.hasNext()) {
next = it.next();
Object value = map.get(next);
append(value, hmacSource);
}
} else if (obj instanceof Enum) {
String strTmp = StringUtils.defaultString(obj.toString(), "");
if (!StringUtils.isBlank(strTmp)) {
hmacSource.append(strTmp).append("#");
}
} else if (isPrimitiveClass(type)) {
Object tmp = ObjectUtils.defaultIfNull(obj, "");
if (!StringUtils.isBlank(tmp.toString())) {
hmacSource.append(tmp).append("#");
}
} else if (obj != null) {
append(obj, hmacSource);
}
} else {
Collection collection = (Collection)obj;
it = collection.iterator();
while(true) {
while(true) {
if (!it.hasNext()) {
continue label95;
}
next = it.next();
if (genericClass != null && isPrimitiveClass(genericClass)) {
hmacSource.append(next).append("#");
} else {
append(next, hmacSource);
}
}
}
}
}
}
}
}
PHP
/**
protected function buildJson($para=null)
{
$vars = $para?'':get_object_vars($this);
unset($vars['response_hmac_fields']);
$data = array();
foreach($vars as $k=>$var){
if(is_scalar($var) && $var !== '' && $var !== null){
$data[$k] = $var;
}else if(is_object($var) && $var instanceof AbstractModel){
$data[$k] =array_filter((array) $var);
}else if(is_array($var)){
$data[$k] =array_filter($var);
}
if(empty($data[$k])){
unset($data[$k]);
}
}
ksort($encrypt_str);
$hmacSource = '';
foreach($encrypt_str as $key => $value){
if (is_array($value)) {
ksort($value);
foreach ($value as $key2 => $value2) {
if (is_object($value2)) {
$value2 = array_filter((array)$value2);
ksort($value2);
foreach ($value2 as $oKey => $oValue) {
$oValue .= '#';
$hmacSource .= trim($oValue);
}
} else if(is_array($value2)){
ksort($value2);
foreach ($value2 as $key3 => $value3) {
if (is_object($value3)) {
$value3 = array_filter((array)$value3);
ksort($value3);
foreach ($value3 as $oKey => $oValue) {
$oValue .= '#';
$hmacSource .= trim($oValue);
}
} else{
$value3 .= '#';
$hmacSource .= trim($value3);
}
}
} else{
$value2 .= '#';
$hmacSource .= trim($value2);
}
}
} else {
$value .= '#';
$hmacSource .= trim($value);
}
}
return $hmacSource;
}
C#
var a = JObject.Parse(order.Json); //Decode the JSON
string hm = string.Join("", GetValue.Getvalue1(a));
public static List Getvalue1(object inp)
{
var res = new List();
var t = new SortedDictionary();
switch (inp.GetType().Name)
{
case "JValue":
res.Add(string.Format("{0}", (inp as JValue).Value));
break;
case "JObject":
foreach (var x in (inp as JObject)) t.Add(x.Key, x.Value);
foreach (var x in t)
{
res.AddRange(Getvalue1(x.Value));
if (x.Value is JObject)
{}
else if (x.Value is JArray)
{ }
else
{
if (String.IsNullOrEmpty(x.Value.ToString()))
{}
else
{ res.Add("#");}
} }
break;
case "JArray":
foreach (var x in (inp as JArray)) res.AddRange(Getvalue1(x));
break;
}
return res;
}
GOLang
//Sort according to the JSON string and return the sequential concatenated string
func GetMapSortJson(jsonstr string) (string, error){
map2 := getMapFromJson(jsonstr)
var recResult string
var erro error
//1.Define slice
s1 := make([]string, 0, len(map2))
//2.Traverse map so as to get key-->in s1
for key := range map2 {
s1 = append(s1, key)
}
//3.Sort "s1"
//使用sort包下的方法直接排序,不用自己写冒泡了。
sort.Strings(s1)
//4. Traverse s1,map
for _, k := range s1 { // _first,then the value
//fmt.Println("type:", reflect.TypeOf(map2[k]))
switch value := map2[k].(type) {
case nil:
fmt.Println(k, "is nil", "null")
case int:
recResult = recResult + strconv.Itoa(value)+"#"
case float64:
recResult = recResult + strconv.FormatFloat(value, 'f', -1, 64)+"#"
case string:
if value != ""{
recResult = recResult + value+"#"
}
case bool:
recResult = recResult +strconv.FormatBool(value)+"#"
case []interface{}:
for _, u := range value {
//fmt.Println("utype:", reflect.TypeOf(u))
if _, ok := u.(map[string]interface {}); ok != true {
recResult = recResult + u.(string) +"#"
}else{
b, berror := json.Marshal(u)
if berror != nil {
erro = berror
}
rec,erro2 := GetMapSortJson(string(b))
if erro2 != nil {
erro = erro2
}
recResult = recResult + rec
}
}
case map[string]interface{}:
b, berror := json.Marshal(value)
if berror != nil {
fmt.Print("berror:", berror)
}
fmt.Println("b:", string(b))
rec,erro2 := GetMapSortJson(string(b))
if erro2 != nil {
erro = erro2
}
recResult = recResult + rec
default:
va := value.(string)
fmt.Println("va:", va)
if va != ""{
recResult = recResult + va+"#"
}
}
}
return recResult,erro
}
Python
def get_sort(dic):
dics2 = ''
dics = dict(sorted(dic.items(),reverse=False))
print("dics-----------------:",dics)
for dics1 in dics :
print(dics1,type(dics[dics1]))
if isinstance(dics[dics1],dict):
dict12 = dics[dics1]
dics2+=get_sort(dict12)
elif isinstance(dics[dics1],str):
if(dics[dics1].strip() !=""):
dics2+=dics[dics1]+'#'
elif type(dics[dics1]).__name__ == "bool":
str_bool = str(dics[dics1])
str_bool_lower = str_bool.lower()
print("bool---------------------;",str_bool_lower)
dics2+=str_bool_lower+'#'
elif type(dics[dics1]).__name__ == "int":
dics2+=str(dics[dics1])+'#'
elif isinstance(dics[dics1],list):
dict12 = dics[dics1]
dic_list = {}
for i in range(len(dict12)):
dic_list.setdefault(i, dict12[i])
print("dic_list------------------:",dic_list)
dics2+=get_sort(dic_list)
return dics2