Java Code Examples for com.google.gson.stream.JsonWriter#beginObject()

The following examples show how to use com.google.gson.stream.JsonWriter#beginObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChannelWriter.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private void writeValidationMessages ( final JsonWriter jw, final Collection<ValidationMessage> messages ) throws IOException
{
    if ( messages == null || messages.isEmpty () )
    {
        return;
    }

    jw.name ( "validationMessages" ).beginArray ();
    for ( final ValidationMessage msg : messages )
    {
        jw.beginObject ();
        jw.name ( "aspectId" ).value ( msg.getAspectId () );
        jw.name ( "severity" ).value ( msg.getSeverity ().toString () );
        jw.name ( "message" ).value ( msg.getMessage () );

        jw.name ( "artifactIds" ).beginArray ();
        for ( final String id : msg.getArtifactIds () )
        {
            jw.value ( id );
        }
        jw.endArray ();

        jw.endObject ();
    }
    jw.endArray ();
}
 
Example 2
Source File: BufferAttribute.java    From BlueMap with MIT License 6 votes vote down vote up
public void writeJson(JsonWriter json) throws IOException {
	json.beginObject();

	json.name("type").value("Float32Array");
	json.name("itemSize").value(itemSize);
	json.name("normalized").value(normalized);

	json.name("array").beginArray();
	for (int i = 0; i < values.length; i++) {
		// rounding and remove ".0" to save string space
		double d = Math.round(values[i] * 10000d) / 10000d;
		if (d == (long) d) json.value((long) d);
		else json.value(d);
	}
	json.endArray();

	json.endObject();
}
 
Example 3
Source File: GsonParceler.java    From Mortar-Flow-Dagger2-demo with MIT License 6 votes vote down vote up
private String encode(Object instance) throws IOException {
    StringWriter stringWriter = new StringWriter();
    JsonWriter writer = new JsonWriter(stringWriter);

    try {
        Class<?> type = instance.getClass();

        writer.beginObject();
        writer.name(type.getName());
        gson.toJson(instance, type, writer);
        writer.endObject();

        return stringWriter.toString();
    } finally {
        writer.close();
    }
}
 
Example 4
Source File: ABIJSON.java    From headlong with Apache License 2.0 6 votes vote down vote up
private static void writeJsonArray(JsonWriter out, String name, TupleType tupleType, boolean[] indexedManifest) throws IOException {
    out.name(name).beginArray();
    for (int i = 0; i < tupleType.elementTypes.length; i++) {
        final ABIType<?> e = tupleType.elementTypes[i];
        out.beginObject();
        addIfValueNotNull(out, NAME, e.getName());
        out.name(TYPE);
        final String type = e.canonicalType;
        if(type.startsWith("(")) { // tuple
            out.value(type.replace(type.substring(0, type.lastIndexOf(')') + 1), TUPLE));
            ABIType<?> base = e;
            while (base instanceof ArrayType) {
                base = ((ArrayType<? extends ABIType<?>, ?>) base).elementType;
            }
            writeJsonArray(out, COMPONENTS, (TupleType) base, null);
        } else {
            out.value(type);
        }
        if(indexedManifest != null) {
            out.name(INDEXED).value(indexedManifest[i]);
        }
        out.endObject();
    }
    out.endArray();
}
 
Example 5
Source File: TypeHandler.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public void write(JsonWriter out,  GsonProperty property, Object value) throws IOException {
    final Class<?> simpleType = property.getType();
    out.beginObject();
    if(value != null) {
        final SparseArray sa = (SparseArray) value;
        if(simpleType.isPrimitive() || isBoxedClass(simpleType)){
            for (int size = sa.size(), i = size - 1; i >= 0; i--) {
                out.name(sa.keyAt(i) + "");
                writePrimitiveOrItsBox(out, simpleType, sa.valueAt(i));
            }
        }else {
            TypeAdapter adapter = getTypeAdapter(simpleType);
            for (int size = sa.size(), i = size - 1; i >= 0; i--) {
                out.name(sa.keyAt(i) + "");
                adapter.write(out, sa.valueAt(i));
            }
        }
    }
    out.endObject();
}
 
Example 6
Source File: JobState.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
protected void propsToJson(JsonWriter jsonWriter)
    throws IOException {
  jsonWriter.beginObject();
  for (String key : this.getPropertyNames()) {
    jsonWriter.name(key).value(this.getProp(key));
  }
  jsonWriter.endObject();
}
 
Example 7
Source File: CloudAppConfigurationGsonFactory.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final JsonWriter out, final CloudAppConfiguration value) throws IOException {
    out.beginObject();
    out.name(CloudConfigurationConstants.APP_NAME).value(value.getAppName());
    out.name(CloudConfigurationConstants.APP_URL).value(value.getAppURL());
    out.name(CloudConfigurationConstants.BOOTSTRAP_SCRIPT).value(value.getBootstrapScript());
    out.name(CloudConfigurationConstants.CPU_COUNT).value(value.getCpuCount());
    out.name(CloudConfigurationConstants.MEMORY_MB).value(value.getMemoryMB());
    out.name(CloudConfigurationConstants.APP_CACHE_ENABLE).value(value.isAppCacheEnable());
    out.name(CloudConfigurationConstants.EVENT_TRACE_SAMPLING_COUNT).value(value.getEventTraceSamplingCount());
    out.endObject();
}
 
Example 8
Source File: CauldronHooks.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
private static <T> void writeChunkCounts(JsonWriter writer, String name, final TObjectIntHashMap<T> map, int max) throws IOException
{
    List<T> sortedCoords = new ArrayList<T>(map.keySet());
    Collections.sort(sortedCoords, new Comparator<T>()
    {
        @Override
        public int compare(T s1, T s2)
        {
            return map.get(s2) - map.get(s1);
        }
    });

    int i = 0;
    writer.name(name).beginArray();
    for (T key : sortedCoords)
    {
        if ((max > 0) && (i++ > max))
        {
            break;
        }
        if (map.get(key) < 5)
        {
            continue;
        }
        writer.beginObject();
        writer.name("key").value(key.toString());
        writer.name("count").value(map.get(key));
        writer.endObject();
    }
    writer.endArray();
}
 
Example 9
Source File: EmployeeGsonWriter.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	Employee emp = EmployeeGsonExample.createEmployee();
	
	//writing on console, we can initialize with FileOutputStream to write to file
	OutputStreamWriter out = new OutputStreamWriter(System.out);
	JsonWriter writer = new JsonWriter(out);
	//set indentation for pretty print
	writer.setIndent("\t");
	//start writing
	writer.beginObject(); //{
	writer.name("id").value(emp.getId()); // "id": 123
	writer.name("name").value(emp.getName()); // "name": "David"
	writer.name("permanent").value(emp.isPermanent()); // "permanent": false
	writer.name("address").beginObject(); // "address": {
		writer.name("street").value(emp.getAddress().getStreet()); // "street": "BTM 1st Stage"
		writer.name("city").value(emp.getAddress().getCity()); // "city": "Bangalore"
		writer.name("zipcode").value(emp.getAddress().getZipcode()); // "zipcode": 560100
		writer.endObject(); // }
	writer.name("phoneNumbers").beginArray(); // "phoneNumbers": [
		for(long num : emp.getPhoneNumbers()) writer.value(num); //123456,987654
		writer.endArray(); // ]
	writer.name("role").value(emp.getRole()); // "role": "Manager"
	writer.name("cities").beginArray(); // "cities": [
		for(String c : emp.getCities()) writer.value(c); //"Los Angeles","New York"
		writer.endArray(); // ]
	writer.name("properties").beginObject(); //"properties": {
		Set<String> keySet = emp.getProperties().keySet();
		for(String key : keySet) writer.name("key").value(emp.getProperties().get(key));//"age": "28 years","salary": "1000 Rs"
		writer.endObject(); // }
	writer.endObject(); // }
	
	writer.flush();
	
	//close writer
	writer.close();
	
}
 
Example 10
Source File: CustomMessageEntry.java    From ForgeHax with MIT License 5 votes vote down vote up
@Override
public void serialize(JsonWriter writer) throws IOException {
  writer.beginObject();
  
  writer.name("msg");
  writer.value(message);
  
  writer.endObject();
}
 
Example 11
Source File: GathererJsonIO.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void write(JsonWriter writer, GathererModule value) throws IOException {
    writer.beginObject();
    writer.name("module").value(value.getName());
    for (Map.Entry<String, String> e : value.getParameters().entrySet()) {
        writer.name(e.getKey()).value(e.getValue());
    }
    writer.endObject();
}
 
Example 12
Source File: JsonSnippet.java    From android with MIT License 5 votes vote down vote up
@Override
public void write(JsonWriter out, JsonSnippet snippet) throws IOException {
    out.beginObject();
    if (!TextUtils.isEmpty(snippet.getTitle())) {
        out.name("title").value(snippet.getTitle());
    }
    if (!TextUtils.isEmpty(snippet.getId())) {
        out.name("id").value(snippet.getId());
    }
    if (!TextUtils.isEmpty(snippet.getCompany())) {
        // CarShare, Spots and Vehicles
        out.name("company").value(snippet.getCompany());
        if (!TextUtils.isEmpty(snippet.getPartnerId())) {
            out.name("partnerId").value(snippet.getPartnerId());
        }
        if (snippet.getAvailable() != Const.UNKNOWN_VALUE) {
            out.name("available").value(snippet.getAvailable());
        }
        if (snippet.getCapacity() != Const.UNKNOWN_VALUE) {
            out.name("capacity").value(snippet.getCapacity());
        }
        if (snippet.getFuel() != Const.UNKNOWN_VALUE) {
            out.name("fuel").value(snippet.getFuel());
        }
    }
    if (snippet.isCheckin()) {
        out.name("isCheckin").value(true);
    }
    if (snippet.isSearch()) {
        out.name("isSearch").value(true);
    }
    out.endObject();
}
 
Example 13
Source File: SparseArrayTypeAdapter.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, SparseArray<T> value) throws IOException {
    out.beginObject();
    if(value != null) {
        for (int size = value.size(), i = size - 1; i >= 0; i--) {
            out.name(value.keyAt(i) + "");
            mAdapter.write(out, value.valueAt(i));
        }
    }
    out.endObject();
}
 
Example 14
Source File: WorkerProcessProtocolZero.java    From buck with Apache License 2.0 5 votes vote down vote up
private static void sendHandshake(JsonWriter writer, int messageId) throws IOException {
  writer.beginArray();
  writer.beginObject();
  writer.name("id").value(messageId);
  writer.name("type").value(TYPE_HANDSHAKE);
  writer.name("protocol_version").value(PROTOCOL_VERSION);
  writer.name("capabilities").beginArray().endArray();
  writer.endObject();
  writer.flush();
}
 
Example 15
Source File: CondorGenerator.java    From pegasus with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter writer, Profiles node) throws IOException {
    writer.beginObject();
    Metadata m = (Metadata) node.get(Profiles.NAMESPACES.metadata);
    if (!m.isEmpty()) {
        for (Iterator it = m.getProfileKeyIterator(); it.hasNext(); ) {
            String key = (String) it.next();
            writer.name(key);
            writer.value((String) m.get(key));
        }
    }
    writer.endObject();
}
 
Example 16
Source File: InitializeParamsTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
public void write(final JsonWriter out, final InitializeParams value) throws IOException {
  if (value == null) {
  	out.nullValue();
  	return;
  }
  
  out.beginObject();
  out.name("processId");
  writeProcessId(out, value.getProcessId());
  out.name("rootPath");
  writeRootPath(out, value.getRootPath());
  out.name("rootUri");
  writeRootUri(out, value.getRootUri());
  out.name("initializationOptions");
  writeInitializationOptions(out, value.getInitializationOptions());
  out.name("capabilities");
  writeCapabilities(out, value.getCapabilities());
  out.name("clientName");
  writeClientName(out, value.getClientName());
  out.name("clientInfo");
  writeClientInfo(out, value.getClientInfo());
  out.name("trace");
  writeTrace(out, value.getTrace());
  out.name("workspaceFolders");
  writeWorkspaceFolders(out, value.getWorkspaceFolders());
  out.endObject();
}
 
Example 17
Source File: TextualComponent.java    From fanciful with MIT License 5 votes vote down vote up
@Override
public void writeJson(JsonWriter writer) throws IOException {
	writer.name(getKey());
	writer.beginObject();
	for (Map.Entry<String, String> jsonPair : _value.entrySet()) {
		writer.name(jsonPair.getKey()).value(jsonPair.getValue());
	}
	writer.endObject();
}
 
Example 18
Source File: ProtocolMessageTypeAdapter.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void write(JsonWriter out, ProtocolMessage value) throws IOException {
   Address src = value.getSource();
   Address dst = value.getDestination();
   String plc = value.getPlaceId();
   String pop = value.getPopulation();
   Date ts = value.getTimestamp();
   Date ct = value.getClientTime();
   String tn = value.getMessageType();
   Integer rv = value.getReflexVersion();
   Address act = value.getActor();

   out.beginObject();
   out.name(ATTR_TTL).value(value.getTimeToLive());
   if (ts != null) {
      out.name(ATTR_TIMESTAMP).value(ts.getTime());
   } else {
      out.name(ATTR_TIMESTAMP).nullValue();
   }

   if (src != null) {
      out.name(ATTR_SOURCE).value(src.getRepresentation());
   } else {
      out.name(ATTR_SOURCE).nullValue();
   }

   if (dst != null) {
      out.name(ATTR_DESTINATION).value(dst.getRepresentation());
   } else {
      out.name(ATTR_DESTINATION).nullValue();
   }

   if (plc != null) {
      out.name(ATTR_PLACEID).value(plc);
   } else {
      out.name(ATTR_PLACEID).nullValue();
   }
   
   if (pop != null) {
      out.name(ATTR_POPULATION).value(pop);
   } else {
      out.name(ATTR_POPULATION).nullValue();
   }

   if (ct != null) {
      out.name(ATTR_CLIENTTIME).value(ct.getTime());
   } else {
      out.name(ATTR_CLIENTTIME).nullValue();
   }

   if (tn != null) {
      out.name(ATTR_TYPENAME).value(tn);
   } else {
      out.name(ATTR_TYPENAME).nullValue();
   }

   if (rv != null) {
      out.name(ATTR_REFLEX_VERSION).value(rv);
   } else {
      out.name(ATTR_REFLEX_VERSION).nullValue();
   }

   if (act != null) {
      out.name(ATTR_ACTOR).value(act.getRepresentation());
   }

   String encoded = value.getEncodedPayloadIfExists();
   if (encoded != null) {
      out.name(ATTR_BUFFER).value(Base64.encodeBase64String(value.getBuffer()));
   } else {
      byte[] bf = value.getBuffer();
      if (bf != null && bf.length > 0) {
         out.name(ATTR_BUFFER).value(Base64.encodeBase64String(value.getBuffer()));
      } else {
         out.name(ATTR_BUFFER).nullValue();
      }
   }

   out.endObject();
}
 
Example 19
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 4 votes vote down vote up
private void writeObject(JsonWriter out, Thing value, boolean isTopLevelObject)
    throws IOException {
  if (value instanceof Enumeration) {
    throw new JsonLdSyntaxException(
        String.format(
            "Enumeration value '%s' cannot be a JSON-LD entity",
            ((Enumeration) value).getFullEnumValue()));
  }
  out.beginObject();
  // @context should be at the top of generated JSON-LD entity if exists.
  writeContext(out, value, isTopLevelObject);
  out.name(JsonLdConstants.TYPE).value(shortNameOf(value.getFullTypeName()));
  ImmutableListMultimap<String, ValueType> properties =
      ((SchemaOrgTypeImpl) value).getAllProperties();
  for (String key : properties.keySet()) {
    if (key.equals(JsonLdConstants.CONTEXT)) {
      continue;
    } else if (key.equals(JsonLdConstants.ID)) {
      out.name(key);
      try {
        String id = value.getJsonLdId();
        if (id == null) {
          out.nullValue();
        } else {
          out.value(id);
        }
      } catch (SchemaOrgException e) {
        throw new JsonLdSyntaxException(
            String.format("Multiple value found for @id in type %s", value.getFullTypeName()));
      }
    } else {
      out.name(shortNameOf(key));
      List<SchemaOrgType> values = ((SchemaOrgTypeImpl) value).getProperty(key);
      if (values.size() == 0) {
        throw new JsonLdSyntaxException(
            String.format(
                "Schema.org type %s's property %s has no value", value.getFullTypeName(), key));
      } else if (values.size() == 1) {
        writeInternal(out, values.get(0));
      } else {
        writeArray(out, values);
      }
    }
  }
  writeReverse(out, value.getJsonLdReverseMap());
  out.endObject();
}
 
Example 20
Source File: StructuredJsonExamplesMessageBodyReaderTest.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
@Test
public void readFromTest() throws IOException, InterruptedException, TimeoutException, ExecutionException {

	final CountDownLatch readThreadIsReadyLatch = new CountDownLatch(1);
	final Exchanger<Example> exampleExchanger = new Exchanger<Example>();

	final PipedInputStream pipedInputStream = new PipedInputStream(); //the reading thread will read from this stream
	final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); //the submission thread will write to this stream

	ExecutorService executorService = Executors.newCachedThreadPool();

	//-------
	//this is the thread that will read the structured examples and compare
	//them to what was submitted by the submitting thread.
	Future<Integer> readingThreadFuture = executorService.submit(new Callable<Integer>() {

		@Override
		public Integer call() throws Exception {

			readThreadIsReadyLatch.countDown(); //signal to the writing thread that this thread is ready.

			Iterable<Example> readStructuredExamples = toTest.readFrom(ExamplesIterable.class, null, null, null, null, pipedInputStream);

			int numExamplesRead = 0;

			LOGGER.trace("Starting to read examples...");

			for (Example readExample : readStructuredExamples) {
				//LOGGER.trace("Read example: {}", readExample.getVWStringRepresentation());

				exampleExchanger.exchange(readExample);
				numExamplesRead++;
			}

			return Integer.valueOf(numExamplesRead);
		}
	});

	readThreadIsReadyLatch.await();

	LOGGER.trace("Writing examples...");

	StructuredExample lastComputedExample = null;
	OutputStreamWriter outputStreamWriter = new OutputStreamWriter(pipedOutputStream, Charsets.UTF_8);

	JsonWriter jsonWriter = new JsonWriter(outputStreamWriter);

	jsonWriter.beginArray();

	Iterable<StructuredExample> structuredExamplesIterable = TestUtils.getStructuredExamplesFromNerTrain();

	for (StructuredExample example : structuredExamplesIterable) {

		if (lastComputedExample != null) {
			Assert.assertEquals(lastComputedExample.getVWStringRepresentation(), exampleExchanger.exchange(null, 2000, TimeUnit.MILLISECONDS).getVWStringRepresentation());
		}

		if (example != StructuredExample.EMPTY_EXAMPLE)
			JsonTestUtils.writeExample(jsonWriter, example);
		else {
			jsonWriter.beginObject();
			jsonWriter.endObject();
		}

		jsonWriter.flush();

		lastComputedExample = example;

	}//end for

	jsonWriter.endArray();

	jsonWriter.flush();

	jsonWriter.close();

	LOGGER.trace("Verifying final example...");

	//don't forget to verify the very last example!
	Assert.assertEquals(lastComputedExample.getVWStringRepresentation(), exampleExchanger.exchange(null, 2000, TimeUnit.MILLISECONDS).getVWStringRepresentation());

	Assert.assertEquals(272274, readingThreadFuture.get().intValue()); //assert that no exceptions where thrown.

}