Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

customize getFields() to return ordered Field Object #615

Merged
merged 1 commit into from
May 6, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions src/main/java/com/alibaba/fastjson/util/DeserializeBeanInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
Expand Down Expand Up @@ -106,6 +102,31 @@ public boolean add(FieldInfo field) {
return true;
}

private static List<Field> getOrderedFields(Class clz) {
Set<Field> visited = new HashSet<Field>();
List<Field> fields = new ArrayList<Field>();
findField0(fields, visited, clz);
return fields;
}

private static void findField0(List<Field> fields, Set<Field> visited, Class<?> clz) {
if (clz == null) {
return;
}
for (Field f : clz.getDeclaredFields()) {
if (Modifier.isPrivate(f.getModifiers())) {
continue;
}
if (visited.add(f)) {
fields.add(f);
}
}
findField0(fields, visited, clz.getSuperclass());
for (Class<?> i : clz.getInterfaces()) {
findField0(fields, visited, i);
}
}

public static DeserializeBeanInfo computeSetters(Class<?> clazz, Type type) {
DeserializeBeanInfo beanInfo = new DeserializeBeanInfo(clazz);

Expand Down Expand Up @@ -273,7 +294,7 @@ public static DeserializeBeanInfo computeSetters(Class<?> clazz, Type type) {
TypeUtils.setAccessible(method);
}

for (Field field : clazz.getFields()) {
for (Field field : getOrderedFields(clazz)) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
Expand Down
39 changes: 39 additions & 0 deletions src/test/java/com/alibaba/json/test/DupFileNameTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.alibaba.json.test;


import com.alibaba.fastjson.JSON;
import junit.framework.TestCase;
import org.junit.Assert;

/**
* 在小米4/c, android-4.4.4;华为P6 android-4.2.2, 会出现反序列化不稳定的问题
*/
public class DupFileNameTest extends TestCase {

public static class A extends B {
public String extra;
}

public static class B {
public String extra;

public String getB() {
return extra;
}
}

public static class C extends B {
public String extra;
}

public void test() {

String text = "{extra:\"s\"}";

A a = JSON.parseObject(text, A.class);
C c = JSON.parseObject(text, C.class);

Assert.assertEquals(a.getB(), c.getB());
}

}