File tree Expand file tree Collapse file tree 4 files changed +60
-6
lines changed
main/java/com/yocto/yoclib/jsonrpc
test/java/com/yocto/yoclib/jsonrpc/tests Expand file tree Collapse file tree 4 files changed +60
-6
lines changed Original file line number Diff line number Diff line change 2020 <version >20240303</version >
2121 </dependency >
2222 <dependency >
23- <groupId >junit</groupId >
24- <artifactId >junit</artifactId >
25- <version >4.13 .2</version >
23+ <groupId >org. junit.jupiter </groupId >
24+ <artifactId >junit-jupiter-engine </artifactId >
25+ <version >5.9 .2</version >
2626 <scope >test</scope >
2727 </dependency >
2828 </dependencies >
Original file line number Diff line number Diff line change 22
33public class JSONRPCException extends Exception {
44
5+ public JSONRPCException (String message ){
6+ super (message );
7+ }
8+
59}
Original file line number Diff line number Diff line change 11package com .yocto .yoclib .jsonrpc ;
22
3- import org .json .JSONObject ;
3+ import org .json .* ;
44
55public abstract class Message {
66
@@ -61,4 +61,38 @@ public JSONObject toObject(){
6161 return this .value ;
6262 }
6363
64+ /**
65+ *
66+ * @param object The object
67+ * @return JSON string
68+ * @throws JSONRPCException An exception
69+ */
70+ public static String encodeJSON (Object object ) throws JSONRPCException {
71+ try {
72+ if (object instanceof JSONObject ){
73+ return ((JSONObject ) object ).toString (0 );
74+ }
75+ if (object instanceof JSONArray ){
76+ return ((JSONArray ) object ).toString (0 );
77+ }
78+ return JSONObject .valueToString (object );
79+ }catch (JSONException e ){
80+ throw new JSONRPCException ("Failed to encode JSON." );
81+ }
82+ }
83+
84+ /**
85+ *
86+ * @param json JSON string
87+ * @return The object
88+ * @throws JSONRPCException An exception
89+ */
90+ public static Object decodeJSON (String json ) throws JSONRPCException {
91+ try {
92+ return new JSONTokener (json ).nextValue ();
93+ }catch (JSONException $e ){
94+ throw new JSONRPCException ("Failed to decode JSON." );
95+ }
96+ }
97+
6498}
Original file line number Diff line number Diff line change 11package com .yocto .yoclib .jsonrpc .tests ;
22
3- import junit .framework .TestCase ;
3+ import com .yocto .yoclib .jsonrpc .JSONRPCException ;
4+ import com .yocto .yoclib .jsonrpc .Message ;
45
5- public class MessageTest extends TestCase {
6+ import org .junit .jupiter .api .Test ;
7+ import static org .junit .jupiter .api .Assertions .*;
8+
9+ public class MessageTest {
10+
11+ @ Test
12+ public void testDecodeEmptyJSON (){
13+ Throwable t = assertThrows (JSONRPCException .class ,() -> Message .decodeJSON ("" ));
14+
15+ assertEquals ("Failed to decode JSON." ,t .getMessage ());
16+ }
17+
18+ @ Test
19+ public void testDecodeJSONString () throws JSONRPCException {
20+ assertEquals ("abc" ,Message .decodeJSON ("\" abc\" " ));
21+ }
622
723}
You can’t perform that action at this time.
0 commit comments