This commit is contained in:
Looly
2021-10-30 02:23:28 +08:00
parent 735325e870
commit 2d1fc30c27
9 changed files with 150 additions and 54 deletions

View File

@@ -4,7 +4,7 @@ import cn.hutool.core.bean.BeanPath;
import cn.hutool.core.collection.ArrayIter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.mutable.MutablePair;
import cn.hutool.core.text.StrJoiner;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
@@ -446,13 +446,13 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
/**
* 加入或者替换JSONArray中指定Index的值如果index大于JSONArray的长度将在指定index设置值之前的位置填充JSONNull.Null
*
* @param index 位置
* @param index 位置
* @param element 值对象. 可以是以下类型: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, or the JSONNull.NULL.
* @return 替换的值,即之前的值
*/
@Override
public Object set(int index, Object element) {
if(index >= size()){
if (index >= size()) {
add(index, element);
}
return this.rawList.set(index, JSONUtil.wrap(element, this.config));
@@ -537,11 +537,11 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
* 支持过滤器,即选择哪些字段或值不写出
*
* @param indentFactor 每层缩进空格数
* @param filter 键值对过滤器
* @param filter 过滤器可以修改值keyindex无法修改
* @return JSON字符串
* @since 5.7.15
*/
public String toJSONString(int indentFactor, Filter<Pair<Integer, Object>> filter){
public String toJSONString(int indentFactor, Filter<MutablePair<Integer, Object>> filter) {
final StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0, filter).toString();
@@ -560,18 +560,19 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
* @param writer writer
* @param indentFactor 缩进因子,定义每一级别增加的缩进量
* @param indent 本级别缩进量
* @param filter 过滤器
* @param filter 过滤器可以修改值keyindex无法修改
* @return Writer
* @throws JSONException JSON相关异常
* @since 5.7.15
*/
public Writer write(Writer writer, int indentFactor, int indent, Filter<Pair<Integer, Object>> filter) throws JSONException {
public Writer write(Writer writer, int indentFactor, int indent, Filter<MutablePair<Integer, Object>> filter) throws JSONException {
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config)
.beginArray();
CollUtil.forEach(this, (value, index)->{
if (null == filter || filter.accept(new Pair<>(index, value))) {
jsonWriter.writeValue(value);
CollUtil.forEach(this, (value, index) -> {
final MutablePair<Integer, Object> pair = new MutablePair<>(index, value);
if (null == filter || filter.accept(pair)) {
jsonWriter.writeValue(pair.getValue());
}
});
jsonWriter.end();
@@ -580,6 +581,7 @@ public class JSONArray implements JSON, JSONGetter<Integer>, List<Object>, Rando
}
// ------------------------------------------------------------------------------------------------- Private method start
/**
* 初始化
*

View File

@@ -7,7 +7,7 @@ import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.mutable.MutablePair;
import cn.hutool.core.map.CaseInsensitiveLinkedMap;
import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.map.MapUtil;
@@ -560,11 +560,11 @@ public class JSONObject implements JSON, JSONGetter<String>, Map<String, Object>
* 支持过滤器,即选择哪些字段或值不写出
*
* @param indentFactor 每层缩进空格数
* @param filter 键值对过滤器
* @param filter 过滤器,同时可以修改编辑键和值
* @return JSON字符串
* @since 5.7.15
*/
public String toJSONString(int indentFactor, Filter<Pair<String, Object>> filter){
public String toJSONString(int indentFactor, Filter<MutablePair<String, Object>> filter) {
final StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0, filter).toString();
@@ -583,17 +583,18 @@ public class JSONObject implements JSON, JSONGetter<String>, Map<String, Object>
* @param writer writer
* @param indentFactor 缩进因子,定义每一级别增加的缩进量
* @param indent 本级别缩进量
* @param filter 过滤器
* @param filter 过滤器,同时可以修改编辑键和值
* @return Writer
* @throws JSONException JSON相关异常
* @since 5.7.15
*/
public Writer write(Writer writer, int indentFactor, int indent, Filter<Pair<String, Object>> filter) throws JSONException {
public Writer write(Writer writer, int indentFactor, int indent, Filter<MutablePair<String, Object>> filter) throws JSONException {
final JSONWriter jsonWriter = JSONWriter.of(writer, indentFactor, indent, config)
.beginObj();
this.forEach((key, value) -> {
if (null == filter || filter.accept(new Pair<>(key, value))) {
jsonWriter.writeField(key, value);
final MutablePair<String, Object> pair = new MutablePair<>(key, value);
if (null == filter || filter.accept(pair)) {
jsonWriter.writeField(pair.getKey(), pair.getValue());
}
});
jsonWriter.end();

View File

@@ -10,6 +10,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.test.bean.JSONBean;
import cn.hutool.json.test.bean.ResultDto;
@@ -67,7 +68,7 @@ public class JSONObjectTest {
@Test
public void toStringTest3() {
JSONObject json = Objects.requireNonNull(JSONUtil.createObj()//
.set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))//
.set("dateTime", DateUtil.parse("2019-05-02 22:12:01")))//
.setDateFormat(DatePattern.NORM_DATE_PATTERN);
Assert.assertEquals("{\"dateTime\":\"2019-05-02\"}", json.toString());
}
@@ -86,14 +87,14 @@ public class JSONObjectTest {
@Test
public void putAllTest() {
JSONObject json1 = JSONUtil.createObj()
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
.set("d", true);
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
.set("d", true);
JSONObject json2 = JSONUtil.createObj()
.set("a", "value21")
.set("b", "value22");
.set("a", "value21")
.set("b", "value22");
// putAll操作会覆盖相同key的值因此a,b两个key的值改变c的值不变
json1.putAll(json2);
@@ -399,7 +400,7 @@ public class JSONObjectTest {
}
@Test
public void aliasTest(){
public void aliasTest() {
final BeanWithAlias beanWithAlias = new BeanWithAlias();
beanWithAlias.setValue1("张三");
beanWithAlias.setValue2(35);
@@ -417,7 +418,7 @@ public class JSONObjectTest {
}
@Test
public void setDateFormatTest(){
public void setDateFormatTest() {
JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
jsonConfig.setOrder(true);
@@ -430,7 +431,7 @@ public class JSONObjectTest {
}
@Test
public void setDateFormatTest2(){
public void setDateFormatTest2() {
JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setDateFormat("yyyy#MM#dd");
jsonConfig.setOrder(true);
@@ -451,7 +452,7 @@ public class JSONObjectTest {
}
@Test
public void setCustomDateFormatTest(){
public void setCustomDateFormatTest() {
JSONConfig jsonConfig = JSONConfig.create();
jsonConfig.setDateFormat("#sss");
jsonConfig.setOrder(true);
@@ -472,7 +473,7 @@ public class JSONObjectTest {
}
@Test
public void getTimestampTest(){
public void getTimestampTest() {
String timeStr = "1970-01-01 00:00:00";
final JSONObject jsonObject = JSONUtil.createObj().set("time", timeStr);
final Timestamp time = jsonObject.get("time", Timestamp.class);
@@ -518,7 +519,7 @@ public class JSONObjectTest {
}
@Test
public void parseBeanSameNameTest(){
public void parseBeanSameNameTest() {
final SameNameBean sameNameBean = new SameNameBean();
final JSONObject parse = JSONUtil.parseObj(sameNameBean);
Assert.assertEquals("123", parse.getStr("username"));
@@ -537,9 +538,11 @@ public class JSONObjectTest {
public static class SameNameBean {
private final String username = "123";
private final String userName = "abc";
public String getUsername() {
return username;
}
@PropIgnore
private final String fieldToIgnore = "sfdsdads";
@@ -547,13 +550,13 @@ public class JSONObjectTest {
return userName;
}
public String getFieldToIgnore(){
public String getFieldToIgnore() {
return this.fieldToIgnore;
}
}
@Test
public void setEntryTest(){
public void setEntryTest() {
final HashMap<String, String> of = MapUtil.of("test", "testValue");
final Set<Map.Entry<String, String>> entries = of.entrySet();
final Map.Entry<String, String> next = entries.iterator().next();
@@ -563,13 +566,13 @@ public class JSONObjectTest {
}
@Test(expected = JSONException.class)
public void createJSONObjectTest(){
public void createJSONObjectTest() {
// 集合类不支持转为JSONObject
new JSONObject(new JSONArray(), JSONConfig.create());
}
@Test
public void floatTest(){
public void floatTest() {
Map<String, Object> map = new HashMap<>();
map.put("c", 2.0F);
@@ -578,7 +581,7 @@ public class JSONObjectTest {
}
@Test
public void accumulateTest(){
public void accumulateTest() {
final JSONObject jsonObject = JSONUtil.createObj().accumulate("key1", "value1");
Assert.assertEquals("{\"key1\":\"value1\"}", jsonObject.toString());
@@ -598,7 +601,7 @@ public class JSONObjectTest {
@Test
public void bigDecimalTest(){
public void bigDecimalTest() {
String jsonStr = "{\"orderId\":\"1704747698891333662002277\"}";
BigDecimalBean bigDecimalBean = JSONUtil.toBean(jsonStr, BigDecimalBean.class);
Assert.assertEquals("{\"orderId\":1704747698891333662002277}", JSONUtil.toJsonStr(bigDecimalBean));
@@ -606,12 +609,12 @@ public class JSONObjectTest {
@Data
static
class BigDecimalBean{
class BigDecimalBean {
private BigDecimal orderId;
}
@Test
public void filterIncludeTest(){
public void filterIncludeTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create().setOrder(true))
.set("a", "value1")
.set("b", "value2")
@@ -623,7 +626,7 @@ public class JSONObjectTest {
}
@Test
public void filterExcludeTest(){
public void filterExcludeTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create().setOrder(true))
.set("a", "value1")
.set("b", "value2")
@@ -633,4 +636,37 @@ public class JSONObjectTest {
final String s = json1.toJSONString(0, (pair) -> false == pair.getKey().equals("b"));
Assert.assertEquals("{\"a\":\"value1\",\"c\":\"value3\",\"d\":true}", s);
}
@Test
public void editTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create().setOrder(true))
.set("a", "value1")
.set("b", "value2")
.set("c", "value3")
.set("d", true);
final String s = json1.toJSONString(0, (pair) -> {
if ("b".equals(pair.getKey())) {
// 修改值为新值
pair.setValue(pair.getValue() + "_edit");
return true;
}
// 除了"b",其他都去掉
return false;
});
Assert.assertEquals("{\"b\":\"value2_edit\"}", s);
}
@Test
public void nullToEmptyTest() {
JSONObject json1 = JSONUtil.createObj(JSONConfig.create().setOrder(true).setIgnoreNullValue(false))
.set("a", null)
.set("b", "value2");
final String s = json1.toJSONString(0, (pair) -> {
pair.setValue(ObjectUtil.defaultIfNull(pair.getValue(), StrUtil.EMPTY));
return true;
});
Assert.assertEquals("{\"a\":\"\",\"b\":\"value2\"}", s);
}
}