Skip to content

Commit

Permalink
fix serialize field priority, for issue #1727
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Aug 13, 2023
1 parent 07a69d4 commit 6602de9
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 2 deletions.
26 changes: 24 additions & 2 deletions core/src/main/java/com/alibaba/fastjson2/writer/FieldWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -402,11 +402,17 @@ public int compareTo(Object o) {
}
}

if (thisMember instanceof Field && otherMember instanceof Method) {
if (thisMember instanceof Field
&& otherMember instanceof Method
&& ((Field) thisMember).getType() == ((Method) otherMember).getReturnType()
) {
return -1;
}

if (thisMember instanceof Method && otherMember instanceof Field) {
if (thisMember instanceof Method
&& otherMember instanceof Field
&& ((Method) thisMember).getReturnType() == ((Field) otherMember).getType()
) {
return 1;
}

Expand Down Expand Up @@ -454,6 +460,22 @@ public int compareTo(Object o) {
}
}

if (thisFieldClass.isPrimitive() && !otherFieldClass.isPrimitive()) {
return -1;
}

if (!thisFieldClass.isPrimitive() && otherFieldClass.isPrimitive()) {
return 1;
}

if (thisFieldClass.getName().startsWith("java.") && !otherFieldClass.getName().startsWith("java.")) {
return -1;
}

if (!thisFieldClass.getName().startsWith("java.") && otherFieldClass.getName().startsWith("java.")) {
return 1;
}

return nameCompare;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.alibaba.fastjson2.issues_1700;

import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue1727 {
@Test
public void test() {
final Bean bean = new Bean();
bean.color = Color.BLUE;

assertEquals("{\"color\":5}", JSON.toJSONString(bean));
}

public enum Color {
RED(1),
YELLOW(3),
BLUE(5);

final Integer value;

Color(Integer value) {
this.value = value;
}
}

@Getter
public static class Bean {
public Color color;

public Integer getColor() {
return color.value;
}
}

@Test
public void test1() {
final Bean1 bean = new Bean1();
bean.color = Color.BLUE;

assertEquals("{\"color\":5}", JSON.toJSONString(bean));
}

@Getter
public static class Bean1 {
public Color color;

public int getColor() {
return color.value;
}
}
}

0 comments on commit 6602de9

Please sign in to comment.