我需要一种非常非常快速的检查字符串是否为JSON的方法.我觉得这不是最好的方法:
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
Run Code Online (Sandbox Code Playgroud)
任何表演爱好者都想改进这种方法吗?
我是JSON的新手.现在,我需要为我的Flash ActionScript 3.0使用JSON.所以我找到了一个用于JSON的库,我看到了术语"反序列化"和"序列化".他们的意思是什么?
serialization json deserialization json-deserialization json-serialization
我有一个使用Jersey构建的REST服务,并部署在AppEngine中.REST服务实现使用application/json媒体类型的动词PUT.数据绑定由Jackson执行.
动词使用JSON表示的企业部门关系
{"name":"myEnterprise", "departments":["HR","IT","SC"]}
Run Code Online (Sandbox Code Playgroud)
在客户端,我使用gson将JSON表示转换为java对象.然后,我将对象传递给我的REST服务,它工作正常.
问题:
当我的JSON表示在集合中只有一个项目时
{"name":"myEnterprise", "departments":["HR"]}
Run Code Online (Sandbox Code Playgroud)
该服务无法反序列化该对象.
ATTENTION: /enterprise/enterprise: org.codehaus.jackson.map.JsonMappingException:
Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at
[Source: org.mortbay.jetty.HttpParser$Input@5a9c5842; line: 1, column: 2
Run Code Online (Sandbox Code Playgroud)
正如其他用户所报告的那样,解决方案是添加标志ACCEPT_SINGLE_VALUE_AS_ARRAY(例如,Jersey:无法从String中反序列化ArrayList的实例).然而,我并不是在控制ObjectMapper,因为在服务方面它是由Jackson透明地制作的.
题:
有没有办法在服务端配置ObjectMapper以启用ACCEPT_SINGLE_VALUE_AS_ARRAY?注释?web.xml中?
代码细节
Java对象:
@XmlRootElement
public class Enterprise {
private String name;
private List<String> departments;
public Enterprise() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getDepartments() {
return departments;
}
public void setDepartments(List<String> departments) {
this.departments …Run Code Online (Sandbox Code Playgroud) 我在使用JSON.NET库对从Facebook返回的数据进行反序列化时遇到了一些麻烦.
从简单的墙贴文件返回的JSON看起来像:
{
"attachment":{"description":""},
"permalink":"http://www.facebook.com/permalink.php?story_fbid=123456789"
}
Run Code Online (Sandbox Code Playgroud)
为照片返回的JSON如下所示:
"attachment":{
"media":[
{
"href":"http://www.facebook.com/photo.php?fbid=12345",
"alt":"",
"type":"photo",
"src":"http://photos-b.ak.fbcdn.net/hphotos-ak-ash1/12345_s.jpg",
"photo":{"aid":"1234","pid":"1234","fbid":"1234","owner":"1234","index":"12","width":"720","height":"482"}}
],
Run Code Online (Sandbox Code Playgroud)
一切都很好,我没有问题.我现在遇到一个来自移动客户端的简单墙帖,其中包含以下JSON,现在反序列化失败,只有一个帖子:
"attachment":
{
"media":{},
"name":"",
"caption":"",
"description":"",
"properties":{},
"icon":"http://www.facebook.com/images/icons/mobile_app.gif",
"fb_object_type":""
},
"permalink":"http://www.facebook.com/1234"
Run Code Online (Sandbox Code Playgroud)
这是我反序列化的类:
public class FacebookAttachment
{
public string Name { get; set; }
public string Description { get; set; }
public string Href { get; set; }
public FacebookPostType Fb_Object_Type { get; set; }
public string Fb_Object_Id { get; set; }
[JsonConverter(typeof(FacebookMediaJsonConverter))]
public List<FacebookMedia> { get; set; }
public string Permalink { get; …Run Code Online (Sandbox Code Playgroud) 我有以下课程:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import java.io.Serializable;
import java.util.HashMap;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Theme implements Serializable {
@JsonProperty
private String themeName;
@JsonProperty
private boolean customized;
@JsonProperty
private HashMap<String, String> descriptor;
//...getters and setters for the above properties
}
Run Code Online (Sandbox Code Playgroud)
当我执行以下代码时:
HashMap<String, Theme> test = new HashMap<String, Theme>();
Theme t1 = new Theme();
t1.setCustomized(false);
t1.setThemeName("theme1");
test.put("theme1", t1);
Theme t2 = new Theme();
t2.setCustomized(true);
t2.setThemeName("theme2");
t2.setDescriptor(new HashMap<String, String>());
t2.getDescriptor().put("foo", "one");
t2.getDescriptor().put("bar", "two");
test.put("theme2", t2);
String json = "";
ObjectMapper mapper = objectMapperFactory.createObjectMapper(); …Run Code Online (Sandbox Code Playgroud) 我正在处理这个问题.假设我有这样的回答:
{
"id":"decaa828741611e58bcffeff819cdc9f",
"statement":"question statement",
"exercise_type":"QUESTION"
}
Run Code Online (Sandbox Code Playgroud)
然后,基于exercise_type属性,我想实例化不同的对象实例(子类ExerciseResponseDTO),所以我创建了这个混合:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "exercise_type")
@JsonSubTypes({
@Type(value = ExerciseChoiceResponseDTO.class, name = "CHOICE"),
@Type(value = ExerciseQuestionResponseDTO.class, name = "QUESTION")})
public abstract class ExerciseMixIn
{}
public abstract class ExerciseResponseDTO {
private String id;
private String statement;
@JsonProperty(value = "exercise_type") private String exerciseType;
// Getters and setters
}
public class ExerciseQuestionResponseDTO
extends ExerciseResponseDTO {}
public class ExerciseChoiceResponseDTO
extends ExerciseResponseDTO {}
Run Code Online (Sandbox Code Playgroud)
所以我创建ObjectMapper如下
ObjectMapper mapper = …Run Code Online (Sandbox Code Playgroud) 我能够序列化和反序列化抽象基类注释的类层次结构
@JsonTypeInfo(
use = JsonTypeInfo.Id.MINIMAL_CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "@class")
Run Code Online (Sandbox Code Playgroud)
但没有@JsonSubTypes列出子类,子类本身相对未注释,只有一个@JsonCreator在构造函数上.ObjectMapper是vanilla,我没有使用mixin.
关于PolymorphicDeserialization和"type id"的 Jackson文档建议(强烈地)我需要在@JsonSubTypes抽象基类上使用注释,或者在mixin上使用它,或者我需要使用ObjectMapper注册子类型.并且有很多SO问题和/或博客帖子都同意.但它确实有效.(这是Jackson 2.6.0.)
那么......我是一个尚未记录的功能的受益者,还是我依赖于无证件行为(可能会改变)或是其他事情还在继续?(我问,因为我真的不希望它成为后两者中的任何一个.但我知道.)
编辑:添加代码 - 和一个评论.评论是:我应该提到我反序列化的所有子类都与基本抽象类在同一个包和同一个jar中.
抽象基类:
package so;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(
use = JsonTypeInfo.Id.MINIMAL_CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "@class")
public abstract class PolyBase
{
public PolyBase() { }
@Override
public abstract boolean equals(Object obj);
}
Run Code Online (Sandbox Code Playgroud)
它的一个子类:
package so;
import org.apache.commons.lang3.builder.EqualsBuilder;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public final class SubA extends PolyBase
{ …Run Code Online (Sandbox Code Playgroud) 设置:
# Pydantic Models
class TMDB_Category(BaseModel):
name: str = Field(alias="strCategory")
description: str = Field(alias="strCategoryDescription")
class TMDB_GetCategoriesResponse(BaseModel):
categories: list[TMDB_Category]
@router.get(path="category", response_model=TMDB_GetCategoriesResponse)
async def get_all_categories():
async with httpx.AsyncClient() as client:
response = await client.get(Endpoint.GET_CATEGORIES)
return TMDB_GetCategoriesResponse.parse_obj(response.json())
Run Code Online (Sandbox Code Playgroud)
问题:
创建响应时使用别名,我想避免它。我只需要这个别名来正确映射传入数据,但在返回响应时,我想使用实际的字段名称。
实际响应:
{
"categories": [
{
"strCategory": "Beef",
"strCategoryDescription": "Beef is ..."
},
{
"strCategory": "Chicken",
"strCategoryDescription": "Chicken is ..."
}
}
Run Code Online (Sandbox Code Playgroud)
预期回应:
{
"categories": [
{
"name": "Beef",
"description": "Beef is ..."
},
{
"name": "Chicken",
"description": "Chicken is ..."
}
}
Run Code Online (Sandbox Code Playgroud) 我是使用JSON数据的新手.
我正在从Web服务中读取数据.发回的查询数据如下:
[["B02001_001E","NAME","state"],
["4712651","Alabama","01"],
["691189","Alaska","02"],
["6246816","Arizona","04"],
["18511620","Florida","12"],
["9468815","Georgia","13"],
["1333591","Hawaii","15"],
["1526797","Idaho","16"],
["3762322","Puerto Rico","72"]]
Run Code Online (Sandbox Code Playgroud)
有没有办法以这样的方式反序列化这些数据,即在没有我首先定义对象是什么的情况下生成基础对象?在上面的示例中,对象由第一行定义:
["B02001_001E","NAME","state"],
Run Code Online (Sandbox Code Playgroud)
通常,Web服务将返回格式化为二维JSON数组的查询数据,其中第一行提供列名,后续行提供数据值.
到目前为止,我已经使用了Json.Net的"JsonConvert.Deserialize(json)"方法,该方法运行得很好,说实话,我不需要更多的东西.
我正在开发一个后台(控制台)应用程序,它不断从不同的URL下载json内容,然后将结果反序列化为.Net对象列表.
using (WebClient client = new WebClient())
{
string json = client.DownloadString(stringUrl);
var result = JsonConvert.DeserializeObject<List<Contact>>(json);
}
Run Code Online (Sandbox Code Playgroud)
上面的简单代码片段似乎并不完美,但它可以完成这项工作.当文件很大(15000个联系人--48 MB文件)时,JsonConvert.DeserializeObject不是解决方案,并且该行抛出异常类型的JsonReaderException.
下载的json是一个数组,这就是样本的样子.Contact是反序列化的json对象的容器类.
[
{
"firstname": "sometext",
"lastname": "sometext"
},
{
"firstname": "sometext",
"lastname": "sometext"
},
{
"firstname": "sometext",
"lastname": "sometext"
},
{
"firstname": "sometext",
"lastname": "sometext"
}
]
Run Code Online (Sandbox Code Playgroud)
我最初的猜测是内存不足.出于好奇,我试图将其解析为JArray,这也导致了同样的异常.
我已经开始深入研究Json.Net文档并阅读类似的线程.由于我还没有设法制作出有效的解决方案,我决定在这里发一个问题.
我很感激任何建议/代码片段,它可以帮助我研究问题,了解更多信息并最终找到解决方案.
谢谢 :)
更新:逐行反序列化时,我得到了同样的错误:"[.路径'',第600003行,第1位." 所以我做的是下载其中两个并在Notepad ++中检查它们.我注意到的是,如果数组长度超过12000,则在第12000个元素之后,"["关闭,另一个数组开始.换句话说,json看起来完全像这样:
[
{
"firstname": "sometext",
"lastname": "sometext"
},
{
"firstname": "sometext",
"lastname": "sometext"
},
{
"firstname": "sometext",
"lastname": "sometext"
},
{
"firstname": "sometext",
"lastname": "sometext"
} …Run Code Online (Sandbox Code Playgroud)