Java源码示例:com.fasterxml.jackson.jr.ob.JSON

示例1
public void convert(StringBuilder appendTo, Map<String, String> eventProperties) {
    Map<String, String> properties = mergeContextMaps(eventProperties);
    if (properties != null && !properties.isEmpty()) {
        try {
            /*
             * -- let's compose an JSON object, then chop off the outermost
             * curly braces
             */
            ObjectComposer<JSONComposer<String>> oc = JSON.std.composeString().startObject();
            for (Entry<String, String> p: properties.entrySet()) {
                if (!exclusions.contains(p.getKey())) {
                    oc.put(p.getKey(), p.getValue());
                }
            }
            String result = oc.end().finish().trim();
            appendTo.append(result.substring(1, result.length() - 1));
        } catch (Exception ex) {
            /* -- avoids substitute logger warnings on startup -- */
            LoggerFactory.getLogger(DefaultPropertiesConverter.class).error("Conversion failed ", ex);
        }
    }
}
 
示例2
@Override
public String toString() {
    /*
     * -- make sure we have set start and end time
     */
    finish();
    try {
        JSONComposer<String> jc = JSON.std.composeString();
        ObjectComposer<JSONComposer<String>> oc = jc.startObject();
        for (Entry<String, Value> value: fields.entrySet()) {
            oc.putObject(value.getKey(), value.getValue().getValue());
        }
        return oc.end().finish();
    } catch (Exception ex) {
        return "{}";
    }
}
 
示例3
public void testNestedMixed() throws Exception
{
    byte[] json = JSON.std.composeBytes()
            .startObject()
                .put("a", 1)
                .startArrayField("arr")
                    .add(1).add(2).add(3)
                .end()
                .startObjectField("ob")
                    .put("x", 3)
                    .put("y", 4)
                    .startArrayField("args").add("none").end()
                .end()
                .put("last", true)
            .end()
            .finish();
    assertEquals("{\"a\":1,\"arr\":[1,2,3],\"ob\":{\"x\":3,\"y\":4,"
            +"\"args\":[\"none\"]},\"last\":true}",
        new String(json, "UTF-8"));
}
 
示例4
public void testPOJOWriterReplacement() throws Exception
{
    final ReaderWriterModifier mod = new RWModifier(NameBean.class,
            new ValueWriter() {
        @Override
        public void writeValue(JSONWriter context, JsonGenerator g,
                Object value) throws IOException {
            NameBean nb = (NameBean) value;
            g.writeString(nb.getFirst() + "-" + nb.getLast());
        }

        @Override
        public Class<?> valueType() {
            return NameBean.class;
        }
    });
    final NameBean input = new NameBean("Foo", "Bar");
    String json = jsonWithModifier(mod).asString(input);
    assertEquals(quote("Foo-Bar"), json);
    // but also verify that no caching occurs wrt global standard variant:
    assertEquals(aposToQuotes("{'first':'Foo','last':'Bar'}"),
            JSON.std.asString(input));
}
 
示例5
public void testMapWithEnumKey() throws Exception
{
    WithEnumMap input = new WithEnumMap(DEF.E, "bar");
    // verify serialization, should be ok:
    String json = JSON.std.asString(input);
    assertEquals(aposToQuotes("{'values':{'E':'bar'}}"), json);

    // and then get it back too
    WithEnumMap result = JSON.std.beanFrom(WithEnumMap.class, json);
    assertNotNull(result);
    Map<DEF, String> map = result.getValues();
    assertNotNull(map);
    assertEquals(1, map.size());
    Map.Entry<?,?> entry = map.entrySet().iterator().next();
    assertEquals("bar", entry.getValue());
    if (!(entry.getKey() instanceof DEF)) {
        fail("Expected key to be of type ABC, is: "+entry.getKey().getClass().getName());
    }
    assertEquals(DEF.E, entry.getKey());
}
 
示例6
public void incrementUsageFor(String moduleId) {
    Preferences node = Preferences.userRoot().node(USAGE_PATH).node(moduleId);
    String json = node.get(MODULE_USAGE_KEY, "");
    try {
        if (isNotBlank(json)) {
            node.put(MODULE_USAGE_KEY, JSON.std.asString(JSON.std.beanFrom(ModuleUsage.class, json).inc()));
        } else {
            node.put(MODULE_USAGE_KEY, JSON.std.asString(ModuleUsage.fistUsage(moduleId)));
        }
        LOG.trace("Usage incremented for module {}", moduleId);
    } catch (IOException e) {
        LOG.error("Unable to increment modules usage statistics", e);
    } finally {
        incrementTotalUsage();
    }
}
 
示例7
public void testCustomDelegatingReader() throws Exception
{
    // First: without handler, will fail to map
    final String doc = "{\"y\" : 3, \"x\": 2 }";
    try {
        JSON.std.beanFrom(Point.class, doc);
        fail("Should not pass");
    } catch (JSONObjectException e) {
        verifyException(e, "$Point");
        verifyException(e, "constructor to use");
    }

    // then with custom, should be fine
    JSON json = jsonWithProvider(new PointReaderProvider());
    Point v = json.beanFrom(Point.class, doc);
    assertEquals(2, v._x);
    assertEquals(3, v._y);
}
 
示例8
public void testSimpleList() throws Exception
{
    List<Object> stuff = new LinkedList<Object>();
    stuff.add("x");
    stuff.add(true);
    stuff.add(123);
    final String exp = "[\"x\",true,123]";
    assertEquals(exp, JSON.std.asString(stuff));
    assertEquals(exp, new String(JSON.std.asBytes(stuff), "ASCII"));

    StringWriter sw = new StringWriter();
    JSON.std.write(stuff, sw);
    assertEquals(exp, sw.toString());

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    JSON.std.write(stuff, bytes);
    assertEquals(exp, bytes.toString("UTF-8"));
}
 
示例9
public void testStringWriterReplacement() throws Exception
{
    final ReaderWriterModifier mod = new RWModifier(String.class,
            new ValueWriter() {
                @Override
                public void writeValue(JSONWriter context, JsonGenerator g,
                        Object value) throws IOException {
                    g.writeString(String.valueOf(value).toUpperCase());
                }

                @Override
                public Class<?> valueType() {
                    return String.class;
                }
    });
    final String input = "foobar";
    String result = jsonWithModifier(mod).asString(input);
    assertEquals(quote("FOOBAR"), result);
    // but also verify that no caching occurs wrt global standard variant:
    assertEquals(quote("foobar"), JSON.std.asString(input));
}
 
示例10
public void testBasicRenameOnDeserialize() throws Exception
{
    final String json = a2q("{'firstName':'Bob','_last':'Burger'}");
    final JSON j = JSON.std
            .with(JSON.Feature.FAIL_ON_UNKNOWN_BEAN_PROPERTY);

    try {
        j.beanFrom(NameSimple.class, json);
        fail("Should not pass");
    } catch (JSONObjectException e) {
        verifyException(e, "Unrecognized JSON property \"firstName\"");
    }
    NameSimple result = JSON_WITH_ANNO.beanFrom(NameSimple.class, json);
    assertEquals("Bob", result._first);
    assertEquals("Burger", result._last);
}
 
示例11
public void testStringReaderReplacement() throws Exception
{
    final String input = quote("foobar");
    assertEquals("foobar", JSON.std.beanFrom(String.class, input));

    // but then with modifier
    final ReaderWriterModifier mod = new RWModifier(String.class,
            new ValueReader(String.class) {
        @Override
        public Object read(JSONReader reader, JsonParser p) throws IOException {
            return p.getText().toUpperCase();
        };
    });
    assertEquals("FOOBAR",
            jsonWithModifier(mod).beanFrom(String.class, input));

    // but also verify that no caching occurs wrt global standard variant:
    assertEquals("foobar", JSON.std.beanFrom(String.class, input));
}
 
示例12
public void testCustomBeanReader() throws Exception
{
    // First: without handler, will fail to map
    try {
        JSON.std.beanFrom(CustomValue.class, "123");
        fail("Should not pass");
    } catch (JSONObjectException e) {
        verifyException(e, ".CustomValue");
        verifyException(e, "constructor to use");
    }

    // then with custom, should be fine
    JSON json = jsonWithProvider(new CustomReaders(0));
    CustomValue v = json.beanFrom(CustomValue.class, "123");
    assertEquals(124, v.value);

    // similarly with wrapper
    CustomValueBean bean = json.beanFrom(CustomValueBean.class,
            aposToQuotes("{ 'custom' : 137 }"));
    assertEquals(138, bean.custom.value);

    // but also ensure we can change registered handler(s)
    JSON json2 = jsonWithProvider(new CustomReaders(100));
    v = json2.beanFrom(CustomValue.class, "123");
    assertEquals(224, v.value);
}
 
示例13
public void testEmptySource() throws Exception {
    try {
        JSON.std.beanFrom(Object.class, "   ");
        fail("Should not pass");
    } catch (JSONObjectException e) {
        verifyException(e, "No content to map due to end-of-input");
    }
}
 
示例14
public void testFailOnDupMapKeys() throws Exception
{
    JSON j = JSON.builder()
            .enable(JSON.Feature.FAIL_ON_DUPLICATE_MAP_KEYS)
            .build();
    assertTrue(j.isEnabled(JSON.Feature.FAIL_ON_DUPLICATE_MAP_KEYS));
    final String json = "{\"a\":1,\"b\":2,\"b\":3,\"c\":4}";
    try {
        /*Map<?,?> map =*/ j.mapFrom(json);
        fail("Should not pass");
    } catch (JSONObjectException e) {
        verifyException(e, "Duplicate key");
    }
}
 
示例15
public void testSimpleBeanMaps() throws Exception
{
    final String INPUT = aposToQuotes("{ 'first':"
            +"{'name':{'first':'Bob','last':'Burger'},'x':13}"
            +", 'second':{'x':-145,'name':{'first':'Billy','last':'Bacon'}}"
            +"}");
    Map<String, TestBean> stuff = JSON.std.mapOfFrom(TestBean.class, INPUT);
    _testSimpleBeanMaps(stuff);

    JsonParser p = parserFor(INPUT);
    stuff = JSON.std.mapOfFrom(TestBean.class, p);
    _testSimpleBeanMaps(stuff);
    p.close();
}
 
示例16
public void convert(StringBuilder appendTo, Map<String, String> mdcCustomFields, Object... arguments) {
	List<CustomField> customFields = getCustomFields(arguments);
	if (!customFields.isEmpty() || !mdcCustomFields.isEmpty()) {
		try {
			if (!embed) {
				appendTo.append(JSON.std.asString(fieldName)).append(":");
			}
			/*
			 * -- no matter whether we embed or not, it seems easier to
			 * compose -- a JSON object from the key/value pairs. -- if we
			 * embed that object, we simply chop off the outermost curly
			 * braces.
			 */
			ObjectComposer<JSONComposer<String>> oc = JSON.std.composeString().startObject();
			for (CustomField cf : customFields) {
				oc.putObject(cf.getKey(), cf.getValue());
			}
			for (Map.Entry<String, String> mdcField : mdcCustomFields.entrySet()) {
				oc.put(mdcField.getKey(), mdcField.getValue());
			}
			String result = oc.end().finish().trim();
			if (embed) {
				/* -- chop off curly braces -- */
				appendTo.append(result.substring(1, result.length() - 1));
			} else {
				appendTo.append(result);
			}
		} catch (Exception ex) {
			/* -- avoids substitute logger warnings on startup -- */
			LoggerFactory.getLogger(DefaultCustomFieldsConverter.class).error("Conversion failed ", ex);
		}
	}
}
 
示例17
public void testFailOnDupMapKeys() throws Exception
{
    JSON j = JSON.builder()
            .enable(JSON.Feature.FAIL_ON_DUPLICATE_MAP_KEYS)
            .build();
    assertTrue(j.isEnabled(JSON.Feature.FAIL_ON_DUPLICATE_MAP_KEYS));
    final String json = "{\"a\":1,\"b\":2,\"b\":3,\"c\":4}";
    try {
        /*TreeNode node =*/ treeJSON.treeFrom(json);
        fail("Should not pass");
    } catch (JSONObjectException e) {
        verifyException(e, "Duplicate key");
    }
}
 
示例18
public void testNameWithLeadingUppers() throws Exception
{
    final String expURL = "http://foo";
    URLBean bean = JSON.std
            .with(JSON.Feature.FAIL_ON_UNKNOWN_BEAN_PROPERTY)
            .beanFrom(URLBean.class, aposToQuotes("{'URL':'"+expURL+"'}"));
    assertEquals(expURL, bean.url);
}
 
示例19
protected String getField(String fieldName, int i) {
    try {
        return JSON.std.mapFrom(getLine(i)).get(fieldName).toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
示例20
public void testComposerWithIndent() throws Exception
{
    String json = JSON.std
            .with(JSON.Feature.PRETTY_PRINT_OUTPUT)
            .composeString()
            .startObject()
                .put("name", "Bill")
            .end()
            .finish();
    assertEquals(aposToQuotes("{\n"
            +"  'name' : 'Bill'\n"
            +"}"),
            json);
}
 
示例21
protected String getField(String fieldName) {
    try {
        return JSON.std.mapFrom(getLastLine()).get(fieldName).toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
示例22
@SuppressWarnings("unchecked")
protected Map<String, Object> getMap(String fieldName) {
    try {
        return (Map<String, Object>) JSON.std.mapFrom(outContent.toString()).get(fieldName);
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
示例23
protected JSON jsonWithTreeCodec() {
        return JSON.builder()
                // 13-Feb-2020, tatu: There are 2 different ways actually..
//            .treeCodec(new JacksonJrsTreeCodec())
                .register(new JrSimpleTreeExtension())
            .build();
    }
 
示例24
private void _verifySimpleMixed(Object ob, String json) throws Exception
{
    assertTrue(ob instanceof Map);
    assertEquals(2, ((Map<?,?>) ob).size());
    Object list = (((Map<?,?>) ob).get("a"));
    assertTrue(list instanceof List<?>);
    
    // actually, verify with write...
    assertEquals(json, JSON.std.asString(ob));
}
 
示例25
protected String getField(String fieldName) {
    try {
        return JSON.std.mapFrom(lastLine()).get(fieldName).toString();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
示例26
public void testSimpleList() throws Exception
{
    Map<String,Object> map = new LinkedHashMap<String,Object>();
    map.put("a", 1);
    map.put("b", 2);
    
    // By default, no indentation
    assertEquals("{\"a\":1,\"b\":2}", JSON.std.asString(map));
    // but with simple change...
    assertEquals("{\n"
            +"  \"a\" : 1,\n"
            +"  \"b\" : 2\n"
            +"}",
            JSON.std.with(JSON.Feature.PRETTY_PRINT_OUTPUT).asString(map));
}
 
示例27
public void testPojoWithIsGetter() throws Exception
{
    assertTrue(JSON.std.isEnabled(JSON.Feature.USE_IS_GETTERS));
    
    String json;

    json = JSON.std.asString(new IsBean());
    // by default, will use 'is-getter':
    assertEquals(aposToQuotes("{'enabled':true,'value':42}"), json);

    // but can disable
    json = JSON.std
            .without(JSON.Feature.USE_IS_GETTERS)
            .asString(new IsBean());
    assertEquals(aposToQuotes("{'value':42}"), json);

    // .... as well as using alternative
    json = JSON.builder()
            .disable(JSON.Feature.USE_IS_GETTERS)
            .build()
            .asString(new IsBean());
    assertEquals(aposToQuotes("{'value':42}"), json);
    
    // and go back as well
    json = JSON.std
            .with(JSON.Feature.USE_IS_GETTERS)
            .asString(new IsBean());
    assertEquals(aposToQuotes("{'enabled':true,'value':42}"), json);
}
 
示例28
public void testSimpleMap() throws Exception
{
    final String INPUT = "{\"a\":1,\"b\":true,\"c\":3}";
    Object ob = JSON.std.anyFrom(INPUT);
    assertTrue(ob instanceof Map);
    assertEquals(3, ((Map<?,?>) ob).size());
    // actually, verify with write...
    assertEquals(INPUT, JSON.std.asString(ob));

    // or, via explicit Map read
    Map<String,Object> stuff = JSON.std.mapFrom(INPUT);
    assertEquals(3, stuff.size());
}
 
示例29
public void testNest() throws Exception
{
    Map<String,Object> stuff = new LinkedHashMap<String,Object>();
    List<Integer> list = new ArrayList<Integer>();
    list.add(123);
    list.add(456);
    stuff.put("first", list);
    Map<String,Object> second = new LinkedHashMap<String,Object>();
    stuff.put("second", second);
    second.put("foo", "bar");
    second.put("bar", new ArrayList<Object>());

    assertEquals("{\"first\":[123,456],\"second\":{\"foo\":\"bar\",\"bar\":[]}}",
            JSON.std.asString(stuff));
}
 
示例30
/**
 * Performs image conversion and output (return, save, and/or upload).
 * @param request scan request object.
 * @return Scan result or null if user cancels.
 * @throws TwainException if failed.
 */
public Result convert(Request request) {
    String requestInJson = JsonUtils.jsonSerialize(request.toJsonObject(), true);
    String result = callNativeFunc(TwainNative.FUNC_image_output, requestInJson);
    if(result != null && result.startsWith("<error:")) {
        throw new TwainException(result);
    }
    try {
        Map<String, Object> root = JSON.std.mapFrom(result);
        return Result.createScanResult(root);
    } catch (Throwable t) {
        throw new TwainException(result, t);
    }
}