////////////////////////////////////////////////////////////////////////////////
// Converters from proto API to JSON output structs.
515611
func apiInstanceToInfo(inst *api.Instance) InstanceInfo {
	return InstanceInfo{
		Pin: common.Pin{
			PackageName: inst.Package,
			InstanceID:  common.ObjectRefToInstanceID(inst.Instance),
		},
		RegisteredBy: inst.RegisteredBy,
		RegisteredTs: UnixTime(google.TimeFromProto(inst.RegisteredTs)),
	}
}
1193470
public String toJson(Map<?, ?> map) {
    StringWriter stringWriter = new StringWriter();
    try {
      toJson(map, stringWriter);
    } catch (IOException e) {
      throw new AssertionError(e); // No I/O writing to a Buffer.
    }
    return stringWriter.toString();
  }
461392
@Override
  public Writable serialize(Object obj, ObjectInspector objInspector)
    throws SerDeException {
    StringBuilder sb = new StringBuilder();
    try {

      StructObjectInspector soi = (StructObjectInspector) objInspector;
      List<? extends StructField> structFields = soi.getAllStructFieldRefs();
      assert (columnNames.size() == structFields.size());
      if (obj == null) {
        sb.append("null");
      } else {
        sb.append(SerDeUtils.LBRACE);
        for (int i = 0; i < structFields.size(); i++) {
          if (i > 0) {
            sb.append(SerDeUtils.COMMA);
          }
          appendWithQuotes(sb, columnNames.get(i));
          sb.append(SerDeUtils.COLON);
          buildJSONString(sb, soi.getStructFieldData(obj, structFields.get(i)),
            structFields.get(i).getFieldObjectInspector());
        }
        sb.append(SerDeUtils.RBRACE);
      }

    } catch (IOException e) {
      LOG.warn("Error generating json text from object.", e);
      throw new SerDeException(e);
    }
    return new Text(sb.toString());
  }
716411
function __serializeType(type, options) {
	let typeHeader = (type) ? TYPE_HEADER[type.toUpperCase()] : [];
	let typeData = new Uint8Array(typeHeader);
	return typeData.buffer;
}
842339
func _proto_marshal(obj proto.Message) []byte {
	buf, err := proto.Marshal(obj)
	if err != nil {
		panic(err)
	}
	return buf
}
565739
public  String sessionOptionsToJson() {
        try {
            return JsonFormat.printer().print(protoBufConfigProto);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
1222177
public String toJson() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        mapper.writeValue(out, this);
        return out.toString();
    }
1110012
function __serializeObject(data, options=DEFAULT_OPTIONS) {
	let dataBuffers = [];
	let allKeys = (options.sort_key === true) ? Object.keys(data).sort() : Object.keys(data);
	// ignore undefined value
	for (let key of allKeys) {
		let subData = data[key];
		if (subData === undefined) continue;

		let subType = __getType(subData, options);
		let subTypeBuffer = __serializeType(subType);
		let keyBuffers = __serializeShortString(key);
		let subDataBuffers = __serializeData(subType, subData, options);
		dataBuffers.push(subTypeBuffer, ...keyBuffers, ...subDataBuffers);
	}
	let length = __getLengthByArrayBuffers(dataBuffers);
	let lengthData = new Uint32Array([length]);
	return [lengthData.buffer, ...dataBuffers];
}
264536
func makeJSONFromProtoStruct(blob []byte) string {
	if len(blob) == 0 {
		return ""
	}

	// Binary proto => internal representation.
	obj := structpb.Struct{}
	if err := proto.Unmarshal(blob, &obj); err != nil {
		return fmt.Sprintf("<not a valid protobuf.Struct - %s>", err)
	}

	// Internal representation => JSON. But JSONPB produces very ugly JSON when
	// using Ident. So we are not done yet...
	ugly, err := (&jsonpb.Marshaler{}).MarshalToString(&obj)
	if err != nil {
		return fmt.Sprintf("<failed to marshal to JSON - %s>", err)
	}

	// JSON => internal representation 2, sigh. Because there's no existing
	// structpb.Struct => map converter and writing one just for the sake of
	// JSON pretty printing is kind of annoying.
	var obj2 map[string]interface{}
	if err := json.Unmarshal([]byte(ugly), &obj2); err != nil {
		return fmt.Sprintf("<internal error when unmarshaling JSON - %s>", err)
	}

	// Internal representation 2 => pretty (well, prettier) JSON.
	pretty, err := json.MarshalIndent(obj2, "", "  ")
	if err != nil {
		return fmt.Sprintf("<internal error when marshaling JSON - %s>", err)
	}
	return string(pretty)
}
1224863
void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
            final boolean includeNullValuedFields, final int depth, final int indentWidth,
            final StringBuilder buf) {
        final boolean prettyPrint = indentWidth > 0;
        final int n = items.size();
        int numDisplayedFields;
        if (includeNullValuedFields) {
            numDisplayedFields = n;
        } else {
            numDisplayedFields = 0;
            for (final Entry<String, Object> item : items) {
                if (item.getValue() != null) {
                    numDisplayedFields++;
                }
            }
        }
        if (objectId == null && numDisplayedFields == 0) {
            buf.append("{}");
        } else {
            buf.append(prettyPrint ? "{\n" : "{");
            if (objectId != null) {
                // id will be non-null if this object does not have an @Id field, but was referenced by
                // another object (need to include ID_TAG)
                if (prettyPrint) {
                    JSONUtils.indent(depth + 1, indentWidth, buf);
                }
                buf.append('"');
                buf.append(JSONUtils.ID_KEY);
                buf.append(prettyPrint ? "\": " : "\":");
                JSONSerializer.jsonValToJSONString(objectId, jsonReferenceToId, includeNullValuedFields, depth + 1,
                        indentWidth, buf);
                if (numDisplayedFields > 0) {
                    buf.append(',');
                }
                if (prettyPrint) {
                    buf.append('\n');
                }
            }
            for (int i = 0, j = 0; i < n; i++) {
                final Entry<String, Object> item = items.get(i);
                final Object val = item.getValue();
                if (val != null || includeNullValuedFields) {
                    final String key = item.getKey();
                    if (key == null) {
                        // Keys must be quoted, so the unquoted null value cannot be a key
                        // (Should not happen -- JSONParser.parseJSONObject checks for null keys)
                        throw new IllegalArgumentException("Cannot serialize JSON object with null key");
                    }
                    if (prettyPrint) {
                        JSONUtils.indent(depth + 1, indentWidth, buf);
                    }
                    buf.append('"');
                    JSONUtils.escapeJSONString(key, buf);
                    buf.append(prettyPrint ? "\": " : "\":");
                    JSONSerializer.jsonValToJSONString(val, jsonReferenceToId, includeNullValuedFields, depth + 1,
                            indentWidth, buf);
                    if (++j < numDisplayedFields) {
                        buf.append(',');
                    }
                    if (prettyPrint) {
                        buf.append('\n');
                    }
                }
            }
            if (prettyPrint) {
                JSONUtils.indent(depth, indentWidth, buf);
            }
            buf.append('}');
        }
    }
92298
function _initConverter(){
                var csvConverter = new Converter_1();
                var started = false;
                var writeStream = process.stdout;
                csvConverter.on("record_parsed",function(rowJSON){
                    if (started){
                        writeStream.write(",\n");
                    }
                    writeStream.write(JSON.stringify(rowJSON));  //write parsed JSON object one by one.
                    if (started === false){
                        started = true;
                    }
                });
                writeStream.write("[\n"); //write array symbol

                csvConverter.on("end_parsed",function(){
                    writeStream.write("\n]"); //end array symbol
                });
                csvConverter.on("error",function(err){
                    console.error(err);
                    process.exit(-1);
                });
                return csvConverter;
            }
1072877
function (yamlJson, cb) {
		
		let all_apis = {};
		let all_errors = {};
		
		let paths = reformatPaths(yamlJson.paths);
		let definitions = yamlJson.definitions;
		let parameters = yamlJson.parameters;
		
		let convertedDefinitions = {};
		let convertedParameters = {};
		
		// convert definitions first
		if (definitions) {
			let definitionsKeys = Object.keys(definitions);
			definitionsKeys.forEach(function (eachDef) {
				convertedDefinitions[eachDef] = convertItem(null, definitions[eachDef], 1); // 1 ??? definitions should never have schema -=-=-=-=-=
			});
		}
		
		// convert parameters then
		if (parameters) {
			let parametersKeys = Object.keys(parameters);
			parametersKeys.forEach(function (eachParam) {
				convertedParameters[eachParam] = convertItem(convertedDefinitions, parameters[eachParam], 1);
			});
			all_apis.commonFields = convertedParameters;
		}
		
		let pathsKeys = Object.keys(paths);
		pathsKeys.forEach(function (eachPath) {
			let methods = paths[eachPath];
			let methodsKeys = Object.keys(methods);
			
			methodsKeys.forEach(function (eachMethod) {
				let apiData = methods[eachMethod];
				
				if (!all_apis[eachMethod]) {
					all_apis[eachMethod] = {};
				}
				
				var mwFile = eachPath.replace(/\\/g, "_").replace(/:/g, "_").replace(/\//g, "_").replace(/[_]{2,}/g, "_").replace(/{/g, "").replace(/}/g, "");
				mwFile = mwFile.toLowerCase();
				if (mwFile[0] === "_") {
					mwFile = mwFile.substring(1);
				}
				mwFile += "_" + eachMethod.toLowerCase() + ".js";
				
				all_apis[eachMethod][eachPath] = {
					_apiInfo: {},
					"mw": '%dirname% + "/lib/mw/' + mwFile + '"'
				};
				let newSoajsApi = all_apis[eachMethod][eachPath];
				
				let params = apiData.parameters;
				
				let group = apiData.tags ? apiData.tags[0] : "";
				newSoajsApi._apiInfo.group = group && group !== '' ? group : "general";
				newSoajsApi._apiInfo.l = apiData.summary;
				newSoajsApi.imfv = convertParams(convertedDefinitions, convertedParameters, params);
			});
		});
		
		// todo: convert errors
		
		return cb({"schema": all_apis, "errors": all_errors});
	}
286117
public static String toJsUnpackFunction(Descriptor protoDescriptor) {
    return Preconditions.checkNotNull(PROTO_TO_JS_UNPACK_FN.get(protoDescriptor.getFullName()));
  }
1051407
def switch_to_json_payload_encoding(call_fn, response_class):
    
    def json_serializer(*args, **kwargs):
        return bytes(json_format.MessageToJson(args[0], True, preserving_proto_field_name=True), "utf-8")
    def json_deserializer(*args, **kwargs):
        resp = response_class()
        json_format.Parse(args[0], resp, True)
        return resp
    call_fn._request_serializer    = json_serializer
    call_fn._response_deserializer = json_deserializer
539298
function() {
  /**
   * Protobuf raw bytes stream parser
   * @private {?JsonStreamParser}
   */
  this.jsonStreamParser_ = null;

  /**
   * The current error message, if any.
   * @private {?string}
   */
  this.errorMessage_ = null;

  /**
   * The current position in the streamed data.
   * @private {number}
   */
  this.streamPos_ = 0;

  /**
   * The current parser state.
   * @private {!State}
   */
  this.state_ = State.INIT;

  /**
   * The currently buffered result (parsed JSON objects).
   * @private {!Array<!Object>}
   */
  this.result_ = [];

  /**
   * Whether the status has been parsed.
   * @private {boolean}
   */
  this.statusParsed_ = false;
}
753810
function Convert (proto, a) {
  if (a instanceof Buffer) {
    return Convert.toString(proto, a)
  } else {
    return Convert.toBuffer(proto, a)
  }
}
987309
function _stringToSignature(string_signatures) {
	const signatures = [];
	for (let signature of string_signatures) {
		// check for properties rather than object type
		if (signature && signature.signature_header && signature.signature) {
			logger.debug('_stringToSignature - signature is protobuf');
		} else {
			logger.debug('_stringToSignature - signature is string');
			const signature_bytes = Buffer.from(signature, 'hex');
			signature = _configtxProto.ConfigSignature.decode(signature_bytes);
		}
		signatures.push(signature);
	}

	return signatures;
}