Java Word - Custom method

How do I obtain String by passing a JSON node to a custom method?

JSON:
{"q1a": ["A. xxxxx", "B. bbbb","C. cccc"]}

Word
<<[TestFunc.test(q1a)]>>

Java program

ReportingEngine.getKnownTypes().add(TestFunc.class);

public class TestFunc{
public static String test(Object arr)
	{
		System.out.println("arr="+arr);
	    return arr.toString();
	}
}

The printed output is: com.aspose.words.internal.zzXpZ@587dde06
I want to get a JSON string

@zhenglifan

To obtain a JSON string by passing a JSON node to your custom method in Java, you need to ensure that your method correctly handles the input type and converts it to a string representation of the JSON.

In your current implementation, the method test(Object arr) is returning the default toString() representation of the object, which is why you are seeing an output like com.aspose.words.internal.zzXpZ@587dde06. Instead, you should convert the input to a JSON string format.

Here’s how you can modify your test method to achieve this:

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestFunc {
    public static String test(Object arr) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // Convert the input object to a JSON string
            return objectMapper.writeValueAsString(arr);
        } catch (Exception e) {
            e.printStackTrace();
            return "Error converting to JSON";
        }
    }
}

In this code:

  • We use the ObjectMapper class from the Jackson library to convert the input object to a JSON string.
  • Make sure to include the Jackson library in your project dependencies to use ObjectMapper.

With this change, when you call <<[TestFunc.test(q1a)]>>, it should return the JSON string representation of the input, which in your case would be {"q1a":["A. xxxxx","B. bbbb","C. cccc"]}.

Make sure to handle any exceptions that may arise during the conversion process to avoid runtime errors.

1 Like

@zhenglifan

Internally, JsonDataSource is mapped to com.aspose.words.net.System.Data.DataSet and related classes. So, there is no way to get a string representation of a particular JSON node to use it with a custom method. Your original query has been addressed in this comment.

1 Like