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

SerializerFeature.WriteNonStringKeyAsString时,Enum双引号加了两次 #1371

Closed
acxlam opened this issue Aug 4, 2017 · 3 comments
Closed
Labels
Milestone

Comments

@acxlam
Copy link

acxlam commented Aug 4, 2017

import static org.assertj.core.api.Assertions.assertThat;

import java.util.Map;
import java.util.TreeMap;

import org.junit.Assert;
import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;

public class FastJsonTest {

	private enum Rooms{
		A, B, C, D ,E ;
	}
	
	@Test
	public void testFastjsonEnum(){
	
	Map<Rooms, Rooms> enumMap = new TreeMap<Rooms, Rooms>();
		
		enumMap.put(Rooms.C, Rooms.D);
		enumMap.put(Rooms.E, Rooms.A);	

		Assert.assertEquals(JSON.toJSONString(enumMap, SerializerFeature.WriteNonStringKeyAsString),
				"{\"C\":\"D\",\"E\":\"A\"}");

	}
	



         @Test
	public void testParsed(){
		
		String oldStyleJson = "{1:'abc', 2:'cde'}";
		
		Gson gson = new Gson();
		
		Map fromJson = gson.fromJson(oldStyleJson, Map.class);
		
		Assert.assertNull(fromJson.get(1));
		
		Assert.assertEquals(fromJson.get("1"), "abc" );
		
		Map parsed = JSON.parseObject(oldStyleJson, Map.class, Feature.IgnoreAutoType, Feature.DisableFieldSmartMatch);

		
		Assert.assertNull(parsed.get(1));
		
		Assert.assertEquals(parsed.get("1"), "abc" );

	}
}

因为浏览器按照RFC7159 I-JSON标准,新的javascript API (IE,FF,chrome均是) JSON.parse要求key必定需要双引号,但是中文不一定需要UTF code,于是我们全局使用SerializerFeature.WriteNonStringKeyAsString,但这个时候enum key变成{""C"":"D",""E"":"A"}了。请注意Gson默认输出已经是I-JSON规范,因此兼容所有浏览器。

另外,因为JSON不存在所谓的数字key,即便是旧的json,key的语义也是String,因此parse(object, Map.class)的默认不应该返回数字的key,Gson此处仍然正确。

希望可以搞个1.3版本来按I-JSON标准处理?

@wenshao wenshao added this to the 1.2.36 milestone Aug 5, 2017
@wenshao wenshao added the bug label Aug 5, 2017
@wenshao
Copy link
Member

wenshao commented Aug 5, 2017

SerializerFeature.WriteNonStringKeyAsString是bug,已处理,后面这个不要紧吧

wenshao added a commit that referenced this issue Aug 5, 2017
wenshao added a commit that referenced this issue Aug 6, 2017
@acxlam
Copy link
Author

acxlam commented Aug 7, 2017

好的,试了下(Map)JSONObject.parse(oldStyleJson).get("1") 正确,第二个可以忽略。

@wenshao
Copy link
Member

wenshao commented Aug 8, 2017

https://github.com/alibaba/fastjson/releases/tag/1.2.36
问题已经修复,请使用新版本

@wenshao wenshao closed this as completed Aug 8, 2017
wenshao added a commit that referenced this issue Jul 17, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants