From 1b443926f56f5f9f2324cde197937348c2d85083 Mon Sep 17 00:00:00 2001 From: nzomkxia Date: Mon, 14 May 2018 14:06:40 +0800 Subject: [PATCH] Merge pull request #1761, add Locale serialize & deserialize support. Fixed #906 --- .../common/json/GenericJSONConverter.java | 21 +++++++++++++++++++ .../alibaba/dubbo/common/json/JSONTest.java | 9 ++++++++ 2 files changed, 30 insertions(+) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/GenericJSONConverter.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/GenericJSONConverter.java index 8a67d711ecf..02553aa5356 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/GenericJSONConverter.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/GenericJSONConverter.java @@ -28,6 +28,7 @@ import java.util.Collection; import java.util.Date; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; @@ -358,6 +359,24 @@ public Object decode(Object jv) throws IOException { } }; GlobalDecoderMap.put(Date.class, d); + + d = new Decoder() { + @Override + public Object decode(Object jv) throws IOException { + if (jv instanceof String) { + String[] items = ((String)jv).split("_"); + if(items.length == 1){ + return new Locale(items[0]); + } + if(items.length == 2){ + return new Locale(items[0], items[1]); + } + return new Locale(items[0], items[1], items[2]); + } + return (Locale)null; + } + }; + GlobalDecoderMap.put(Locale.class, d); } @Override @@ -407,6 +426,8 @@ public void writeValue(Object obj, JSONWriter jb, boolean writeClass) throws IOE writeValue(item, jb, writeClass); } jb.arrayEnd(); + } else if(obj instanceof Locale) { + jb.valueString(obj.toString()); } else { jb.objectBegin(); diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JSONTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JSONTest.java index bc45e87f246..cf631eebb6b 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JSONTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JSONTest.java @@ -24,6 +24,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import static org.junit.Assert.assertEquals; @@ -169,6 +170,14 @@ public void testParse2Arguments() throws Exception { assertEquals(test[0], 1); } + @Test + public void testLocale() throws Exception { + Locale obj = Locale.US; + String str = JSON.json(obj); + assertEquals("\"en_US\"", str); + assertEquals(obj, JSON.parse(str, Locale.class)); + } + public static class Bean1 { public int[] array; private String name, displayName;