|
| 1 | +package org.json.junit; |
| 2 | + |
| 3 | +import static org.junit.Assert.*; |
| 4 | + |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +import org.json.*; |
| 8 | +import org.junit.*; |
| 9 | + |
| 10 | +/** |
| 11 | + * Note: This file is saved as UTF-8. Do not save as ASCII or the tests will |
| 12 | + * fail. |
| 13 | + * |
| 14 | + */ |
| 15 | +public class JSONObjectLocaleTest { |
| 16 | + /** |
| 17 | + * JSONObject built from a bean with locale-specific keys. |
| 18 | + * In the Turkish alphabet, there are 2 versions of the letter "i". |
| 19 | + * 'eh' I ı (dotless i) |
| 20 | + * 'ee' İ i (dotted i) |
| 21 | + * A problem can occur when parsing the public get methods for a bean. |
| 22 | + * If the method starts with getI... then the key name will be lowercased |
| 23 | + * to 'i' in English, and 'ı' in Turkish. |
| 24 | + * We want the keys to be consistent regardless of locale, so JSON-Java |
| 25 | + * lowercase operations are made to be locale-neutral by specifying |
| 26 | + * Locale.ROOT. This causes 'I' to be universally lowercased to 'i' |
| 27 | + * regardless of the locale currently in effect. |
| 28 | + */ |
| 29 | + @Test |
| 30 | + public void jsonObjectByLocaleBean() { |
| 31 | + |
| 32 | + MyLocaleBean myLocaleBean = new MyLocaleBean(); |
| 33 | + |
| 34 | + /** |
| 35 | + * This is just the control case which happens when the locale.ROOT |
| 36 | + * lowercasing behavior is the same as the current locale. |
| 37 | + */ |
| 38 | + Locale.setDefault(new Locale("en")); |
| 39 | + JSONObject jsonen = new JSONObject(myLocaleBean); |
| 40 | + assertEquals("expected size 2, found: " +jsonen.length(), 2, jsonen.length()); |
| 41 | + assertEquals("expected jsonen[i] == beanI", "beanI", jsonen.getString("i")); |
| 42 | + assertEquals("expected jsonen[id] == beanId", "beanId", jsonen.getString("id")); |
| 43 | + |
| 44 | + /** |
| 45 | + * Without the JSON-Java change, these keys would be stored internally as |
| 46 | + * starting with the letter, 'ı' (dotless i), since the lowercasing of |
| 47 | + * the getI and getId keys would be specific to the Turkish locale. |
| 48 | + */ |
| 49 | + Locale.setDefault(new Locale("tr")); |
| 50 | + JSONObject jsontr = new JSONObject(myLocaleBean); |
| 51 | + assertEquals("expected size 2, found: " +jsontr.length(), 2, jsontr.length()); |
| 52 | + assertEquals("expected jsontr[i] == beanI", "beanI", jsontr.getString("i")); |
| 53 | + assertEquals("expected jsontr[id] == beanId", "beanId", jsontr.getString("id")); |
| 54 | + } |
| 55 | +} |
0 commit comments