如果您对net.sf.json.JSONException:Unterminatedstringatcharacter2101感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解net.sf.jso
如果您对net.sf.json.JSONException: Unterminated string at character 2101感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解net.sf.json.JSONException: Unterminated string at character 2101的各种细节,此外还有关于atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy、c# – NewtonSoft json转换器“unterminated String,expected delimiter:”; “、com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value异常、com.fasterxml.jackson.core.JsonGenerationException的实例源码的实用技巧。
本文目录一览:- net.sf.json.JSONException: Unterminated string at character 2101
- atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy
- c# – NewtonSoft json转换器“unterminated String,expected delimiter:”; “
- com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value异常
- com.fasterxml.jackson.core.JsonGenerationException的实例源码
net.sf.json.JSONException: Unterminated string at character 2101
在用json提交数据的时候发现有时候会报这个异常,经过跟踪后台以及录入的数据发现用户在录入完成后习惯在句末加一个回车符,导致json格式不符合要求。根据这个发现找出的解决办法是将该变量中所有的换行符进行替换。在展示的时候使用硬换行就可以了。
var str=str_temp.replace(/[\n]/ig,'');将该变量中出现的所有的换行符转换成空格。
atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy
atitit.解决net.sf.json.JSONExceptionThereisacycleinthehierarchy
1.环境:使用hibernate4跟个,要不个哪的对象系列化成个json的时候儿有这个问题了... 1
2.原因::hb默认的lazy方式造成的当有关联对象的时候儿... 1
3.#---解决::lazy=false(推荐).. 1
4.别的有以下的四个方法可以解决hibernate的序列化问题 2
5.BeanUtils.copyProperties可以解决... 2
6.属性过滤器PropertyFilter 2
7.简单属性过滤器setExclusions法 3
8.JsonBeanProcessor法 4
9.设置JSON-LIB的setCycleDetectionStrategy属性让其自己处理循环(ati测试不生效O81).. 4
10.参考 5
1.环境:使用hibernate4跟个,要不个哪的对象系列化成个json的时候儿有这个问题了...
2.原因::hb默认的lazy方式造成的当有关联对象的时候儿...
3.#---解决::lazy=false(推荐)..
<!--o7oati-->
<!--many开头的是代表该表持有外键-->
<!--class可以不写,因为根据name的值computer(属性),会通过反射自动找到属于哪个类的-->
<many-to-onename="prgrm"insert="false"update="false"lazy="false">
<columnname="progarmme_id"/>
</many-to-one>
作者::老哇的爪子Attilax艾龙,EMAIL:1466519819@qq.com
4.别的有以下的四个方法可以解决hibernate的序列化问题
1domain类实现JSONString接口
2建立JsonConfig实例,并配置属性排除列表
3用属性过滤器
4写一个自定义的JsonBeanProcessor
5.BeanUtils.copyProperties可以解决...
GvProgrammestp=(GvProgramme)arg1;
GvProgrammeo=newGvProgramme();
BeanUtils.copyProperties(o,stp);
6.属性过滤器PropertyFilter
//先过滤对set集合的拆解4JsonConfigconfig=newJsonConfig();5config.setJsonPropertyFilter(newPropertyFilter(){6@Override7publicbooleanapply(Objectarg0,Stringarg1,Objectarg2){8if(arg1.equals("shoppingCarts")){9returntrue;10}else{11returnfalse;12}13}14});15//将数据转换成Json数据16JSONArrayjsonObject=JSONArray.fromObject(listCarts,config);17System.out.println(jsonObject.toString());
7.简单属性过滤器setExclusions法
2.第二种方法通过jsonconfig实例,对包含和需要排除的属性进行方便添加删除
[java]viewplaincopyprint?
5publicclassperson{<br>
6privateStringname;<br>
7privateStringlastname;<br>
8privateAddressaddress;<br>
9<br>
10//getters&setters<br>
11}<br>
12<br>
13JsonConfigjsonConfig=newJsonConfig();<br>
14jsonConfig.setExclusions(newString[]{"address"});<br>
15Personbean=/*initialize*/;<br>
16JSOnjson=JSONSerializer.toJSON(bean,jsonConfig);
注意:这种方法不区分目标类,就是说如果有2个bean当中都存在“address”属性,那么采用这种方法,这两个bean中的address属性都将被排除
3.使用propertyFilter可以允许同时对需要排除的属性和类进行控制,这种控制还可以是双向的,也可以应用到json字符串到java对象
publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse){
LibtypeDAOlibtypeDAO=newLibtypeDAO();
List<Libtype>list=libtypeDAO.findAll();
JsonConfigjsonConfig=newJsonConfig();//建立配置文件
jsonConfig.setIgnoreDefaultExcludes(false);//设置默认忽略
jsonConfig.setExcludes(newString[]{"libs"});//此处是亮点,只要将所需忽略字段加到数组中即可,在上述案例中,所要忽略的是“libs”,那么将其添到数组中即可,在实际测试中,我发现在所返回数组中,存在大量无用属性,如“multipartRequestHandler”,“servletWrapper”,那么也可以将这两个加到忽略数组中.
8.JsonBeanProcessor法
4.最后来看JsonBeanProcessor,这种方式和实现JsonString很类似,返回一个代表原来的domain类的合法JSONOBJECT
1.设置JSON-LIB让其过滤掉引起循环的字段:
9.设置JSON-LIB的setCycleDetectionStrategy属性让其自己处理循环(ati测试不生效O81)..
2.
3.省事但是数据过于复杂的话会引起数据溢出或者效率低下。
publicActionForwardexecute(ActionMappingmapping,HttpServletResponseresponse){
LibtypeDAOlibtypeDAO=newLibtypeDAO();
List<Libtype>list=libtypeDAO.findAll();
JsonConfigjsonConfig=newJsonConfig();//建立配置文件
jsonConfig.setIgnoreDefaultExcludes(false);//设置默认忽略
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);//此处是亮点,不过经过测试,第2种方法有些悲剧,虽然可以使用,但其结果貌似循环数次,至于为啥,还请高人指点。
JSONArrayjsonArray=JSONArray.fromObject(list,jsonConfig);//加载配置文件
returnnull;
}
3.
10.参考
关于json-libThereisacycleinthehierarchy!问题的3种解决办法_威廉庄园_williambryantliu的和讯博客.htm
使用json-lib完成json的序列化和反序列化-话别深秋-博客频道-CSDN.NET.htm
hibernate中lazy的使用-TOYOE-博客园.htm
c# – NewtonSoft json转换器“unterminated String,expected delimiter:”; “
我面临的问题是反序列化每次都不起作用,即使我发出相同的请求.我不知道如何修复它,因为try.catch没有做任何更好的事情.
此外,当我试图解析一个非常大的响应(20个json对象)时,程序永远不会工作.
我自己搜索了问题,但我不知道解决方案..
Unterminated string. Expected delimiter: “. Path ‘drinks[0].strMeasure4’,line 3,position 720.
是我得到的错误之一,它永远不会是一样的.
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.sockets; using System.Text; using System.Threading.Tasks; using ConsoleApplication1; namespace TCPclient { class Program { static void Main(string[] args) { TcpClient client = new TcpClient(); client.Connect("www.thecocktaildb.com",80); // geen http string request = getRequestCoctail("margarita"); NetworkStream stream = client.GetStream(); byte[] buffer = Encoding.Default.GetBytes(request); stream.Write(buffer,buffer.Length); StringBuilder message = new StringBuilder(); int numberOfBytesRead = 0; byte[] receiveBuffer = new byte[1024]; do { numberOfBytesRead = stream.Read(receiveBuffer,receiveBuffer.Length); message.AppendFormat("{0}",Encoding.ASCII.GetString(receiveBuffer,numberOfBytesRead)); } while (stream.DataAvailable); string response = message.ToString(); //Console.WriteLine("Response: \n" + response); response = response.Substring(response.IndexOf("\r\n\r\n")); try { dynamic jsonData = JsonConvert.DeserializeObject(response); List<Drink> drankjes = new List<Drink>(); for (int i = 0; i < jsonData.drinks.Count; i++) { try { string id = jsonData.drinks[i].idDrink; string drink = jsonData.drinks[i].strDrink; string category = jsonData.drinks[i].strCategory; string instructions = jsonData.drinks[i].strInstructions; string glass = jsonData.drinks[i].strGlass; Console.WriteLine(glass); var d = new Drink(id,drink,category,instructions); drankjes.Add(d); } catch (Exception) { Console.WriteLine("error"); } } } catch (Exception e) { Console.WriteLine(e.Message); } //Console.WriteLine(jsonData.drinks.Count); //Console.WriteLine(jsonData.drinks.Count); get ammount of drinks. Console.ReadKey(); } //www.thecocktaildb.com/api/json/v1/1/lookup.PHP?i=15679 private static string getRequestCoctail(string coctail) { ///api/json/v1/1/search.PHP?s=margarita return $"GET /api/json/v1/1/search.PHP?s=godfather HTTP/1.1\r\n" + "Host: www.thecocktaildb.com\r\n\r\n"; } private static string GetMetaDataCocktail(dynamic jsonData) { dynamic drink = jsonData.drinks[0]; return $"DrinkID : {drink.idDrink} \nDrinkName : {drink.strDrink} \nInstructions : {drink.strInstructions}"; } private static Drink GenerateNewDrink(dynamic jsonData) { Console.WriteLine(jsonData.idDrink,jsonData.strDrink,jsonData.strCategory,jsonData.strInstructions); return new Drink(jsonData.idDrink,"",jsonData.strInstructions); } } }
编辑:
我添加了饮料类:
class Drink { public readonly string drinkId; public readonly string strDrink; public readonly string strCategory; public readonly string strInstructions; public readonly string strGlass; public Drink(string drinkId,string strDrink,string strCategory,string strInstructions) { this.drinkId = drinkId; this.strDrink = strDrink; this.strCategory = strCategory; this.strInstructions = strInstructions; } public Drink(string drinkId,string strGlass,string strInstructions) { this.drinkId = drinkId; this.strDrink = strDrink; this.strCategory = strCategory; this.strGlass = strGlass; this.strInstructions = strInstructions; } } }
我尝试过:
http://www.thecocktaildb.com/api/json/v1/1/search.php?s=godfather
它好了5次,然后我得到了这个错误我收到的json.
第6次也很好.
http://pastebin.com/c0d29L0S(更好的格式,然后下面的粘贴)
反序列化对象时意外结束.路径’饮料[1] .strIngredient1′,第3行,第1243位.
{"drinks":[ {"idDrink":"11423","strDrink":"Godfather","strCategory":"Ordinary Drink","strAlcoholic":"Alcoholic","strGlass":"Old-fashioned glass","strInstructions":"Pour ingredients into an old-fashioned glass over ice and serve. (Bourbon may be substituted for scotch,if preferred.)","strDrinkThumb":null,"strIngredient1":"Scotch","strIngredient2":"Amaretto","strIngredient3":"","strIngredient4":"","strIngredient5":"","strIngredient6":"","strIngredient7":"","strIngredient8":"","strIngredient9":"","strIngredient10":"","strIngredient11":"","strIngredient12":"","strIngredient13":"","strIngredient14":"","strIngredient15":"","strMeasure1":"1 1\/2 oz ","strMeasure2":"3\/4 oz ","strMeasure3":" ","strMeasure4":" ","strMeasure5":" ","strMeasure6":" ","strMeasure7":" ","strMeasure8":"","strMeasure9":"","strMeasure10":"","strMeasure11":"","strMeasure12":"","strMeasure13":"","strMeasure14":"","strMeasure15":"","dateModified":null },{"idDrink":"11538","strDrink":"J. R.'s Godfather","strInstructions":"In an old-fashioned glass almost filled with ice cubes,combine both of the ingredients. Stir to mix the flavors.","strIngredient1":
我理解为什么它现在出错,JSON无效,但这是我收到的回复.所以我用来获得响应的代码是错的..对吧?
编辑3:
相同的请求,良好的JSON响应:
http://pastebin.com/e3WNxz0W
现在该程序可以运行,但它是不存在的.
解决方法
结果很可能是批量发送的,即转移编码是“分块”的,但是你天真的读者只能获得第一个块并使用它,而不是等待更多.这可能会在请求之间发生变化(例如,在直接传递时分块,在缓存后不分块,反之亦然).所以最后,不要重新发明轮子,只需使用WebClient.
Read up the RFC section 3.6.1:
3.6.1 Chunked Transfer Coding
The chunked encoding modifies the body of a message in order to
transfer it as a series of chunks,each with its own size indicator,
followed by an OPTIONAL trailer containing entity-header fields. This
allows dynamically produced content to be transferred along with the
information necessary for the recipient to verify that it has
received the full message.
当您遇到这样的问题时,请尝试将代码拆分为较小的部分,然后检查这些部分是否能够提供预期的结果.
在您的情况下,您的HTTP下载显然似乎不完整,因此您不能真正责怪JSON解析器吐出错误(因为它们是有效的).
com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value异常
springboot对象返回,一直报生成json异常,经过检查,发现是自己在做xss防护时对出参进行了json的处理(copy代码不可取,囧)
异常信息
这里进行了出参处理了,但实际上只要对入参处理就行了,把这个类改成入参处理即可
public class XssStringJsonSerializer extends JsonSerializer<String> {
@Override
public Class<String> handledType() {
return String.class;
}
@Override
public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (s == null) {
String encodedValue = StringEscapeUtils.escapeHtml4(s);
jsonGenerator.writeString(encodedValue);
}
}
即
//入参检查
public class XssStringJsonSerializer extends JsonDeserializer<String> {
public XssStringJsonSerializer(Class<String> string) {
super();
}
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException
{
String value = jsonParser.getValueAsString();
if (value != null){
return StringEscapeUtils.escapeHtml4(value.toString());
}
return value;
}
@Override
public Class<String> handledType() {
return String.class;
}
}
耽误了一小时代码排除,xss防护copy别人代码的。。。没理解就用的下场。。
com.fasterxml.jackson.core.JsonGenerationException的实例源码
@Test public void testWriteValueOutputStreamObject() { boolean status = true; String[] stringArray = new String[1]; stringArray[0] = "abc"; new MockUp<ObjectWriter>() { @Mock public void writeValue(OutputStream out,Object value) throws IOException,JsonGenerationException,JsonMappingException { } }; try { StandardobjectWriter.writeValue(outputStream,stringArray); } catch (IOException e) { status = false; } Assert.assertTrue(status); }
@Test public void testNullInComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent(null); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out,new Writer() { @Override public void writeContents(JsonGenerator generator,ObjectMapper objectMapper) throws JsonGenerationException,JsonMappingException,IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME,new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator,aComment); } }); assertEquals("Null values should not be output.","{\"canEdit\":false,\"canDelete\":false}",out.toString()); }
@Override public Response toResponse(JsonProcessingException exception) { if (exception instanceof JsonGenerationException) { LOG.error("Error generating JSON",exception); return Response.serverError().build(); } if (exception.getMessage().startsWith("No suitable constructor found")) { LOG.error("Unable to deserialize the specific type",exception); return Response.serverError().build(); } LOG.info(exception.getLocalizedMessage()); return Response .status(Response.Status.BAD_REQUEST) .type(MediaType.APPLICATION_JSON_TYPE) .entity(createUnauditedErrorStatus(UUID.randomUUID(),ExceptionType.JSON_PARSING,exception.getoriginalMessage())) .build(); }
@CsapDoc ( notes = { "Summary status of host" },linkTests = "default" ) @RequestMapping ( { "/status" } ) public ObjectNode status () throws JsonGenerationException,IOException { ObjectNode healthJson = jacksonMapper.createObjectNode(); if ( Application.isJvmInManagerMode() ) { healthJson.put( "error","vmHealth is only enabled on CsAgent urls." ); } else { healthJson = csapApp.statusForAdminorAgent( ServiceAlertsEnum.ALERT_LEVEL ); } return healthJson; }
@Override public void serialize(SerializablePagedCollection pagedCol,JsonGenerator jgen,SerializerProvider provider) throws IOException,JsonGenerationException { if (pagedCol != null) { jgen.writeStartObject(); jgen.writeFieldName("list"); jgen.writeStartObject(); serializePagination(pagedCol,jgen); serializeContext(pagedCol,jgen); jgen.writeObjectField("entries",pagedCol.getCollection()); serializeIncludedSource(pagedCol,jgen); jgen.writeEndobject(); jgen.writeEndobject(); } }
@CsapDoc ( notes = { "refer to /api/appication/service" },linkTests = { "ServletSample" },linkPaths = { "/serviceStop/ServletSample_8041" },linkPostParams = { "userid=someDeveloper,pass=changeMe,cluster=changeMe,clean=clean" } ) @RequestMapping ( "/serviceStop/{serviceName}" ) @Deprecated public JsonNode serviceStop ( @PathVariable ( "serviceName" ) String serviceName_port,@RequestParam ( value = "cluster",defaultValue = "" ) String cluster,@RequestParam ( value = "clean",defaultValue = "" ) String clean,@RequestParam ( SpringAuthCachingFilter.USERID ) String userid,@RequestParam ( SpringAuthCachingFilter.PASSWORD ) String inputPass,HttpServletRequest request ) throws JsonGenerationException,IOException { logger.debug( "DeprecatedApi - use /api/application/service/kill" ); if ( Application.isJvmInManagerMode() ) { return applicationApi.serviceKill( serviceName_port,stripOffLifecycle(cluster),clean,"keepLogs",userid,inputPass,request ); } else { ArrayList<String> services = new ArrayList<>() ; services.add( serviceName_port ) ; return agentApi.serviceKill( services,null,request ); } }
public void serialize(JsonGenerator jgen,beakerObjectConverter boc) throws JsonGenerationException,IOException { jgen.writeStartObject(); jgen.writeNumberField("width",w); if (theStyle!=null) jgen.writeStringField("thestyle",theStyle); if (theClass!=null) jgen.writeStringField("theclass",theClass); jgen.writeArrayFieldStart("payload"); for (Object o : payload) { if ( o instanceof dashRow ) { ((dashRow) o).serialize(jgen,boc); } else if (!boc.writeObject(o,jgen,true)) jgen.writeObject(o.toString()); } jgen.writeEndarray(); jgen.writeEndobject(); }
/** * Writes the list of <code>Principal</code>s to the JSONGenerator. * * @param principals * the list of principals to be written. */ private void writePrincipals(List<Principal> principals) throws JsonGenerationException,IOException { if (principals.size() == 1 && principals.get(0).equals(Principal.All)) { writeJsonkeyvalue(JsonDocumentFields.PRINCIPAL,Principal.All.getId()); } else { writeJsonObjectStart(JsonDocumentFields.PRINCIPAL); Map<String,List<String>> principalsByScheme = groupPrincipalByScheme(principals); List<String> principalValues; for (Map.Entry<String,List<String>> entry : principalsByScheme.entrySet()) { principalValues = principalsByScheme.get(entry.getKey()); if (principalValues.size() == 1) { writeJsonkeyvalue(entry.getKey(),principalValues.get(0)); } else { writeJsonArray(entry.getKey(),principalValues); } } writeJsonObjectEnd(); } }
/** * A callback so a JsonGenerator can be used inline but exception are handled here * @param outStream OutputStream * @param writer The writer interface * @throws IOException */ public void withWriter(OutputStream outStream,Writer writer) throws IOException { try { JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(outStream,encoding); writer.writeContents(generator,objectMapper); } catch (JsonMappingException error) { logger.error("Failed to write Json output",error); } catch (JsonGenerationException generror) { logger.error("Failed to write Json output",generror); } }
/** * Writes the list of conditions to the JSONGenerator. * * @param conditions * the conditions to be written. */ private void writeConditions(List<Condition> conditions) throws JsonGenerationException,IOException { Map<String,ConditionsByKey> conditionsByType = groupConditionsByTypeAndKey(conditions); writeJsonObjectStart(JsonDocumentFields.CONDITION); ConditionsByKey conditionsByKey; for (Map.Entry<String,ConditionsByKey> entry : conditionsByType .entrySet()) { conditionsByKey = conditionsByType.get(entry.getKey()); writeJsonObjectStart(entry.getKey()); for (String key : conditionsByKey.keySet()) { writeJsonArray(key,conditionsByKey.getConditionsByKey(key)); } writeJsonObjectEnd(); } writeJsonObjectEnd(); }
@Test public void testSerializeComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent("<b>There it is</b>"); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out,aComment); } }); assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\"")); }
@Override public void writeMetaData(OutputStream out,ResourceWithMetadata resource,Map<String,ResourceWithMetadata> allApiResources) throws IOException { final Object result = processResult(resource,allApiResources); assistant.getJsonHelper().withWriter(out,IOException { objectMapper.writeValue(generator,result); } }); }
@Test public void logShouldSwallowExceptions() throws JsonProcessingException { SystemFragment frag = SystemFragment.empty(); Mockito.when(analyzerMock.analyzeSystem()).thenReturn(frag); Mockito.when(objectMapperMock.writeValueAsstring(frag)).thenThrow(Mockito.mock(JsonGenerationException.class)); logSnitch.log(); Mockito.verify(analyzerMock).analyzeSystem(); Mockito.verify(objectMapperMock).writeValueAsstring(frag); }
@Override public void serialize(CategoryEntity value,JsonGenerator gen,SerializerProvider provider) throws IOException { if (null == value) { throw new JsonGenerationException("Could not serialize object to json,input object to serialize is null"); } StringWriter writer = new StringWriter(); mapper.writeValue(writer,value); gen.writeFieldName(writer.toString()); }
@Override public void serialize(JSOnoptions value,SerializerProvider provider) throws IOException,JsonGenerationException { if (value.opaque != null) { jgen.writeObject(value.opaque); } else { jgen.writeTree(value.root); } }
@CsapDoc ( notes = "Summary information for application. On Admin nodes,it will include packages,clusters,trending configuration and more." ) @RequestMapping ( "/summary" ) public ObjectNode applicationSummary () throws JsonGenerationException,IOException { return application.getCapabilitySummary( true ); }
private void print(MapVector mapVector,int count) throws JsonGenerationException,IOException{ if(PRINT_OUTPUT){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonWriter jsonWriter = new JsonWriter(baos,true,false); FieldReader reader = new SingleMapReaderImpl(mapVector); for(int index = 0; index < count; index++){ reader.setPosition(index); jsonWriter.write(reader); } System.out.println(baos.toString()); } }
@CsapDoc ( notes = { "Uses active in past 60 minutes" },linkTests = "default" ) @GetMapping ( USERS_URL ) public ArrayNode usersActive () throws JsonGenerationException,IOException { return activeUsers.getActive(); }
@CsapDoc ( notes = { KILL_SERVICES_URL + ": api for stoping specified service","param services: 1 or more service port is required.","Parameter: clean - optional - omit or leave blank to not delete files" },linkTests = { "ServletSample" },linkPaths = { KILL_SERVICES_URL },linkPostParams = { USERID_PASS_ParaMS + "clean=clean,keepLogs=keepLogs,services=ServletSample_8041,auditUserid=blank" } ) @PostMapping ( KILL_SERVICES_URL ) public ObjectNode serviceKill ( @RequestParam ArrayList<String> services,@RequestParam ( required = false ) String clean,@RequestParam ( required = false ) String keepLogs,@RequestParam ( SpringAuthCachingFilter.USERID ) String apiUserid,@RequestParam ( defaultValue = "" ) String auditUserid,IOException { logger.info( "auditUserid: {},apiUserid: {},services: {} clean: {},keepLogs: {} ",auditUserid,apiUserid,services,keepLogs ); ObjectNode apiResponse = serviceCommands.killRequest( apiUserid,keepLogs,auditUserid ); ObjectNode securityResponse = (ObjectNode) request .getAttribute( SpringAuthCachingFilter.SEC_RESPONSE_ATTRIBUTE ); apiResponse.set( "security",securityResponse ); return apiResponse; }
@CsapDoc ( notes = { START_SERVICES_URL + ": api for starting specified service","parameter: services: 1 or more service port is required.","optional: deployId - start will only be issued IF deployment id specified is successful. If not specified start will be issued.","optional: clean - omit or leave blank to not delete files" },linkPaths = { START_SERVICES_URL },linkPostParams = { USERID_PASS_ParaMS + "commandArguments=blank,runtime=blank,auditUserid=blank,startClean=blank,startNoDeploy=blank,hotDeploy=blank,deployId=blank" } ) @PostMapping ( START_SERVICES_URL ) public ObjectNode serviceStart ( @RequestParam ArrayList<String> services,@RequestParam ( required = false ) String commandArguments,@RequestParam ( required = false ) String runtime,@RequestParam ( required = false ) String hotDeploy,@RequestParam ( required = false ) String startClean,@RequestParam ( required = false ) String noDeploy,String deployId,IOException { logger.info( "auditUserid: {},apiUserid:{},services: {} javaOpts: {},runtime: {},hotDeploy: {},startClean: {},startNoDeploy: {} ",commandArguments,runtime,hotDeploy,startClean,noDeploy ); return serviceCommands.startRequest( apiUserid,noDeploy,deployId ); }
@Override public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException,JsonGenerationException { /** * Custom object separator (Default is " : ") to make it easier to compare state dumps with other * ethereum client implementations */ jg.writeraw(": "); }
@Test public void testSerializeMultipleObjects() throws IOException { final Collection<Comment> allComments = new ArrayList<Comment>(); Comment aComment = new Comment(); aComment.setContent("<b>There it is</b>"); allComments.add(aComment); aComment = new Comment(); aComment.setContent("<p>I agree with the author</p>"); allComments.add(aComment); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out,allComments); } }); assertTrue(out.toString().contains("content\":\"<b>There it is</b>")); assertTrue(out.toString().contains("content\":\"<p>I agree with the author</p>")); }
@CsapDoc ( notes = { "Health Check for Http Monitoring via Eman,hyperic,nagios,and others.","* Agent service only" },linkTests = "default" ) @RequestMapping ( value = { "/hostStatus","/vmStatus" } ) @Deprecated public JsonNode hostStatus () throws JsonGenerationException,IOException { return agentApi.runtime(); }
@CsapDoc ( notes = { "refer to /api/appication/service" },linkPaths = { "/serviceDeploy/ServletSample_8041" },linkPostParams = { USERID_PASS_ParaMS + "performStart=true,mavenId=com.your.group:Servlet3Sample:1.0.3:war,cluster=changeMe" } ) @PostMapping ( "/serviceDeploy/{serviceName}" ) @Deprecated public JsonNode serviceDeploy ( @PathVariable ( "serviceName" ) String serviceName_port,@RequestParam ( "mavenId" ) String mavenId,@RequestParam ( value = "performStart",defaultValue = "true" ) boolean performStart,IOException { logger.debug( "DeprecatedApi - use /api/application/serviceDeploy" ); return applicationApi.serviceDeploy( serviceName_port,mavenId,performStart,request ); }
@Override public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException,JsonGenerationException { /** * Custom object separator (Default is " : ") to make it easier to compare state dumps with other * ethereum client implementations */ jg.writeraw(": "); }
@Override public void serialize(LogicalExpression value,JsonGenerationException { StringBuilder sb = new StringBuilder(); ExpressionStringBuilder esb = new ExpressionStringBuilder(); value.accept(esb,sb); jgen.writeString(sb.toString()); }
public String writeResponse(final Object respons) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out,IOException { objectMapper.writeValue(generator,respons); } }); return out.toString(); }
@Override public void serialize(JSOnoptions value,JsonGenerationException { if (value.opaque != null) { jgen.writeObject(value.opaque); } else { jgen.writeTree(value.root); } }
/** * Renders the result of an execution. * * @param res WebScriptResponse * @param toSerialize result of an execution * @throws IOException */ default void renderjsonResponse(final WebScriptResponse res,final Object toSerialize,final JacksonHelper jsonHelper) throws IOException { jsonHelper.withWriter(res.getoutputStream(),new JacksonHelper.Writer() { @Override public void writeContents(JsonGenerator generator,toSerialize); } }); }
public static void generateVertexLine(StringWriter sw,ObjectMapper mapper,VertexBean vBean) throws JsonGenerationException,IOException { sw.getBuffer().setLength(0); sw.append('V'); // Record type sw.append('='); mapper.writeValue(sw,vBean); sw.append('#'); int hashCode = sw.toString().hashCode(); sw.append(toHex(hashCode)); sw.append('\n'); }
public static void generateEdgeLine(StringWriter sw,EdgeBean eBean) throws JsonGenerationException,IOException { sw.getBuffer().setLength(0); sw.append('E'); // Record type sw.append('='); mapper.writeValue(sw,eBean); sw.append('#'); int hashCode = sw.toString().hashCode(); sw.append(toHex(hashCode)); sw.append('\n'); }
@Override public void serialize(AbstractEntity value,JsonGenerationException { if (value != null) jgen.writeNumber(value.getId()); else jgen.writeNull(); }
@Override public String serialize(ISpatialReference value) throws IOException,JsonGenerationException { String json = this.geometryMapper.writeSpatialReference(value); return json; }
@Override public void serialize(T value,JsonGenerationException { String content = serialize(value); JsonNode node = this.objectMapper.readTree(content); jgen.writeTree(node); }
private void getJSONStringFromMap(JsonGenerator jg,Map map,String pf) throws JsonGenerationException,IOException { jg.writeStartObject(); Iterator iter = (Iterator) map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); // Iterate over Map and write key-value jg.writeFieldName(entry.getKey().toString()); // write Key in a Map writeValue(jg,entry.getValue(),pf); // write value in a Map } jg.writeEndobject(); }
private String getJSONString(JsonGenerator jg,PdxInstance pdxInstance) throws JsonGenerationException,IOException { jg.writeStartObject(); List<String> pdxFields = pdxInstance.getFieldNames(); for (String pf : pdxFields) { Object value = pdxInstance.getField(pf); jg.writeFieldName(pf); writeValue(jg,value,pf); } jg.writeEndobject(); return null; }
private <T> void getJSONStringFromArray1(JsonGenerator jg,T[] array,IOException { jg.writeStartArray(); for (T obj : array) { writeValue(jg,obj,pf); } jg.writeEndarray(); }
private void getJSONStringFromCollection(JsonGenerator jg,Collection<?> coll,IOException { jg.writeStartArray(); for (Object obj : coll) { writeValue(jg,pf); } jg.writeEndarray(); }
public static void getJsonFromPrimitiveBoolArray(JsonGenerator jg,boolean[] array,IOException { jg.writeStartArray(); for (boolean obj : array) { jg.writeBoolean(obj); } jg.writeEndarray(); }
今天关于net.sf.json.JSONException: Unterminated string at character 2101的介绍到此结束,谢谢您的阅读,有关atitit.解决net.sf.json.JSONException There is a cycle in the hierarchy、c# – NewtonSoft json转换器“unterminated String,expected delimiter:”; “、com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value异常、com.fasterxml.jackson.core.JsonGenerationException的实例源码等更多相关知识的信息可以在本站进行查询。
本文标签: