Skip to content

Commit ba246a0

Browse files
committed
Add example snippets
1 parent 60bf6d3 commit ba246a0

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed

README.md

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,60 @@ This yocLibrary enables your project to encode and decode JSON-RPC messages in J
2121
### Serialization
2222

2323
```java
24-
//TODO
24+
import com.yocto.yoclib.jsonrpc.JSONRPCException;
25+
import com.yocto.yoclib.jsonrpc.Message;
26+
27+
import org.json.JSONArray;
28+
import org.json.JSONObject;
29+
30+
Message message = Message.createRequestMessageV1(123,"getInfo",new JSONArray().put("payments")); // Create request (version 1.0)
31+
Message message = Message.createNotificationMessageV1("notificationEvent",new JSONArray().put("payed")); // Create notification (version 1.0)
32+
Message message = Message.createResponseMessageV1(123,new JSONObject().put("payments",new JSONArray().put("$10.12").put("$23.45").put("$12.34"))); // Create response (version 1.0)
33+
34+
Object object = message.toObject();
35+
36+
try{
37+
String json = Message.encodeJSON(object);
38+
}catch(JSONRPCException e){
39+
//Handle encoding exception
40+
}
2541
```
2642

2743
### Deserialization
2844

2945
```java
30-
//TODO
46+
import com.yocto.yoclib.jsonrpc.JSONRPCException;
47+
import com.yocto.yoclib.jsonrpc.Message;
48+
49+
import java.util.Scanner;
50+
51+
import org.json.JSONArray;
52+
import org.json.JSONObject;
53+
54+
Scanner scanner = new Scanner(System.in);
55+
56+
String json = scanner.nextLine(); // Get request body
57+
58+
try{
59+
Object object = Message.decodeJSON(json);
60+
}catch(JSONRPCException e){
61+
//Handle decoding exception
62+
}
63+
64+
if(Message.isBatch(object)){
65+
JSONArray arr = (JSONArray) object;
66+
for(Object element : arr.toList()){
67+
try{
68+
Message message = Message.parse(element);
69+
}catch(JSONRPCException e){
70+
//Handle message exception
71+
}
72+
}
73+
}else{
74+
try{
75+
Message message = Message.parse(object);
76+
}catch(JSONRPCException e){
77+
//Handle message exception
78+
}
79+
}
3180
```

0 commit comments

Comments
 (0)