Skip to content

Commit

Permalink
add new method JSON.parseObject(String, Type, JSONReader.Context),refer
Browse files Browse the repository at this point in the history
  • Loading branch information
jihuayu authored and wenshao committed Jul 3, 2024
1 parent 12b40c7 commit e8a1910
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSON.java
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,37 @@ static <T> T parseObject(String text, Type type) {
}
}

/**
* Parses the json string as {@link T}. Returns {@code null}
* if received {@link String} is {@code null} or empty or its content is null.
*
* @param text the specified string to be parsed
* @param type the specified actual type of {@link T}
* @param context the specified custom context
* @return {@link T} or {@code null}
* @throws JSONException If a parsing error occurs
* @since 2.0.52
*/
@SuppressWarnings("unchecked")
static <T> T parseObject(String text, Type type, JSONReader.Context context) {
if (text == null || text.isEmpty()) {
return null;
}

final ObjectReader<T> objectReader = context.getObjectReader(type);

try (JSONReader reader = JSONReader.of(text, context)) {
T object = objectReader.readObject(reader, type, null, 0);
if (reader.resolveTasks != null) {
reader.handleResolveTasks(object);
}
if (reader.ch != EOI && (context.features & IgnoreCheckClose.mask) == 0) {
throw new JSONException(reader.info("input not end"));
}
return object;
}
}

/**
* Parses the json string as {@link T}. Returns
* {@code null} if received {@link String} is {@code null} or empty.
Expand Down
10 changes: 10 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/JSONTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,15 @@ public void test_parse_object_typed_set_long() {
}
}

@Test
public void test_parse_object_with_context() {
JSONReader.Context context = JSONFactory.createReadContext();
User user = JSON.parseObject("{\"id\":1,\"name\":\"fastjson\"}",
(Type) User.class, context);
assertEquals(1, user.id);
assertEquals("fastjson", user.name);
}

@Test
public void test_array_empty() {
List list = (List) JSON.parse("[]");
Expand Down Expand Up @@ -678,6 +687,7 @@ public void test_writeTo_0() {
assertEquals("[1]",
new String(out.toByteArray()));
}

@Test
public void test_writeTo_0_f() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Expand Down

0 comments on commit e8a1910

Please sign in to comment.