diff --git a/pom.xml b/pom.xml index 877cb55..7c4922f 100644 --- a/pom.xml +++ b/pom.xml @@ -20,9 +20,9 @@ 20240303 - junit - junit - 4.13.2 + org.junit.jupiter + junit-jupiter-engine + 5.9.2 test diff --git a/src/main/java/com/yocto/yoclib/jsonrpc/JSONRPCException.java b/src/main/java/com/yocto/yoclib/jsonrpc/JSONRPCException.java index 8b98754..84316e0 100644 --- a/src/main/java/com/yocto/yoclib/jsonrpc/JSONRPCException.java +++ b/src/main/java/com/yocto/yoclib/jsonrpc/JSONRPCException.java @@ -2,4 +2,8 @@ public class JSONRPCException extends Exception{ + public JSONRPCException(String message){ + super(message); + } + } \ No newline at end of file diff --git a/src/main/java/com/yocto/yoclib/jsonrpc/Message.java b/src/main/java/com/yocto/yoclib/jsonrpc/Message.java index d8701b1..f05e8de 100644 --- a/src/main/java/com/yocto/yoclib/jsonrpc/Message.java +++ b/src/main/java/com/yocto/yoclib/jsonrpc/Message.java @@ -1,6 +1,6 @@ package com.yocto.yoclib.jsonrpc; -import org.json.JSONObject; +import org.json.*; public abstract class Message{ @@ -61,4 +61,38 @@ public JSONObject toObject(){ return this.value; } + /** + * + * @param object The object + * @return JSON string + * @throws JSONRPCException An exception + */ + public static String encodeJSON(Object object) throws JSONRPCException { + try{ + if(object instanceof JSONObject){ + return ((JSONObject) object).toString(0); + } + if(object instanceof JSONArray){ + return ((JSONArray) object).toString(0); + } + return JSONObject.valueToString(object); + }catch(JSONException e){ + throw new JSONRPCException("Failed to encode JSON."); + } + } + + /** + * + * @param json JSON string + * @return The object + * @throws JSONRPCException An exception + */ + public static Object decodeJSON(String json) throws JSONRPCException { + try{ + return new JSONTokener(json).nextValue(); + }catch(JSONException $e){ + throw new JSONRPCException("Failed to decode JSON."); + } + } + } \ No newline at end of file diff --git a/src/test/java/com/yocto/yoclib/jsonrpc/tests/MessageTest.java b/src/test/java/com/yocto/yoclib/jsonrpc/tests/MessageTest.java index ee2aea2..7c04403 100644 --- a/src/test/java/com/yocto/yoclib/jsonrpc/tests/MessageTest.java +++ b/src/test/java/com/yocto/yoclib/jsonrpc/tests/MessageTest.java @@ -1,7 +1,23 @@ package com.yocto.yoclib.jsonrpc.tests; -import junit.framework.TestCase; +import com.yocto.yoclib.jsonrpc.JSONRPCException; +import com.yocto.yoclib.jsonrpc.Message; -public class MessageTest extends TestCase{ +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class MessageTest{ + + @Test + public void testDecodeEmptyJSON(){ + Throwable t = assertThrows(JSONRPCException.class,() -> Message.decodeJSON("")); + + assertEquals("Failed to decode JSON.",t.getMessage()); + } + + @Test + public void testDecodeJSONString() throws JSONRPCException { + assertEquals("abc",Message.decodeJSON("\"abc\"")); + } } \ No newline at end of file