Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
JSONMessageCodec.java
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package io.flutter.plugin.common;
6
7import androidx.annotation.Nullable;
8import java.nio.ByteBuffer;
9import org.json.JSONException;
10import org.json.JSONObject;
11import org.json.JSONTokener;
12
13/**
14 * A {@link MessageCodec} using UTF-8 encoded JSON messages.
15 *
16 * <p>This codec is guaranteed to be compatible with the corresponding <a
17 * href="https://api.flutter.dev/flutter/services/JSONMessageCodec-class.html">JSONMessageCodec</a>
18 * on the Dart side. These parts of the Flutter SDK are evolved synchronously.
19 *
20 * <p>Supports the same Java values as {@link JSONObject#wrap(Object)}.
21 *
22 * <p>On the Dart side, JSON messages are handled by the JSON facilities of the <a
23 * href="https://api.dartlang.org/stable/dart-convert/JSON-constant.html">dart:convert</a> package.
24 */
25public final class JSONMessageCodec implements MessageCodec<Object> {
26 // This codec must match the Dart codec of the same name in package flutter/services.
27 public static final JSONMessageCodec INSTANCE = new JSONMessageCodec();
28
29 private JSONMessageCodec() {}
30
31 @Override
32 @Nullable
33 public ByteBuffer encodeMessage(@Nullable Object message) {
34 if (message == null) {
35 return null;
36 }
37 final Object wrapped = JSONUtil.wrap(message);
38 if (wrapped instanceof String) {
39 return StringCodec.INSTANCE.encodeMessage(JSONObject.quote((String) wrapped));
40 } else {
41 return StringCodec.INSTANCE.encodeMessage(wrapped.toString());
42 }
43 }
44
45 @Override
46 @Nullable
47 public Object decodeMessage(@Nullable ByteBuffer message) {
48 if (message == null) {
49 return null;
50 }
51 try {
52 final String json = StringCodec.INSTANCE.decodeMessage(message);
53 final JSONTokener tokener = new JSONTokener(json);
54 final Object value = tokener.nextValue();
55 if (tokener.more()) {
56 throw new IllegalArgumentException("Invalid JSON");
57 }
58 return value;
59 } catch (JSONException e) {
60 throw new IllegalArgumentException("Invalid JSON", e);
61 }
62 }
63}
static sk_sp< GrTextureProxy > wrapped(skiatest::Reporter *reporter, GrRecordingContext *rContext, GrProxyProvider *proxyProvider, SkBackingFit fit)
Object decodeMessage(@Nullable ByteBuffer message)
ByteBuffer encodeMessage(@Nullable Object message)
static Object wrap(@Nullable Object o)
Definition JSONUtil.java:63
static final StringCodec INSTANCE
ByteBuffer encodeMessage(@Nullable String message)
String decodeMessage(@Nullable ByteBuffer message)
uint8_t value
Win32Message message