View Javadoc
1   package edu.jiangxin.apktoolbox.convert.protobuf.unsupervised;
2   
3   import com.google.protobuf.WireFormat;
4   import org.apache.commons.collections.CollectionUtils;
5   import org.json.JSONObject;
6   
7   import java.util.List;
8   
9   public class ProtobufUtils {
10      public static JSONObject getJsonObject(DecoderResult decoderResult) {
11          JSONObject jsonObject = new JSONObject();
12          jsonObject.put("byteRange", decoderResult.getByteRange());
13          jsonObject.put("fieldNumber", decoderResult.getFieldNumber());
14  
15          List<DecoderResult> subResults = decoderResult.getSubResults();
16  
17          if (CollectionUtils.isEmpty(subResults)) {
18              jsonObject.put("type", typeToString(decoderResult.getType(), false));
19              jsonObject.put("content", decoderResult.getContent());
20          } else {
21              jsonObject.put("type", typeToString(decoderResult.getType(), true));
22              for (DecoderResult subResult : decoderResult.getSubResults()) {
23                  jsonObject.append("content", getJsonObject(subResult));
24              }
25          }
26          return jsonObject;
27      }
28  
29      private static String typeToString(int type, boolean hasSubResults) {
30          return switch (type) {
31              case WireFormat.WIRETYPE_VARINT -> "varint";
32              case WireFormat.WIRETYPE_LENGTH_DELIMITED -> {
33                  if (hasSubResults) {
34                      yield "protobuf";
35                  }
36                  yield "string";
37              }
38              case WireFormat.WIRETYPE_FIXED32 -> "fixed32";
39              case WireFormat.WIRETYPE_FIXED64 -> "fixed64";
40              default -> "unknown";
41          };
42      }
43  }