我知道 JSONArray 和 JSONObject 的区别。
我对反序列化它们有疑问。
在反序列化对象类型为 Cluster 的数组时,我可以使用 fromJson 对象来完成。
相反,在反序列化 Topic 类型的对象时,我不得不使用 JSONParser。
有什么区别?我不知道什么时候使用 JSONParser。
仅供引用 Cluster 类:
package com.example.android_json;
public class Cluster {
public String title;
public String stories;
public String src;
public Cluster()
{
}
public Cluster(String title,String stories,String src)
{
this.title = title;
this.stories = stories;
this.src = src;
}
}
主题类:
package com.example.news_android_mobile_application_cd;
import java.util.ArrayList;
import java.util.List;
import checkdeck.news.ui_services_java_api.rest.model.MiniCluster;
public class Topic {
public Topic()
{
}
public Topic(String TopicID,String TopicName,ArrayList<MiniCluster> miniCluster,ArrayList<String> clusterid)
{
topicName = TopicName;
topicID = TopicID;
clusterList = miniCluster;
clusterID = clusterid;
}
String topicID;
String topicName;
boolean isMandatory;
List<MiniCluster> clusterList = new ArrayList<MiniCluster>();
ArrayList<String> clusterID = new ArrayList<String>();
}
反序列化代码如下——
对于集群类:
Gson gson1 = new Gson();
Cluster[] clusters = gson1.fromJson(json, Cluster[].class);
对于主题类:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject responseObj = parser.parse(json).getAsJsonObject();
String topicID = responseObj.getAsJsonPrimitive("topicID").getAsString();
String topicName = responseObj.getAsJsonPrimitive("topicName").getAsString();
Boolean isMandatory = responseObj.getAsJsonPrimitive("isMandatory").getAsBoolean();
JsonArray cList = responseObj.getAsJsonArray("clusterList");
JsonArray cID = responseObj.getAsJsonArray("clusterID");
List<MiniCluster> clusterList = new ArrayList<MiniCluster>();
ArrayList<String> clusterID = new ArrayList<String>();
for(int i=0;i<cID.size();i++)
{
clusterList.add(gson.fromJson(cList.get(i), MiniCluster.class));
clusterID.add(cID.get(i).toString());
}
The JsonData to be deserialised
提前致谢。
最佳答案
这是我用来反序列化您的 json 的最少代码。
package com.foo.examples;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class JsonDeser {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String jsonStr = JsonManupulation.readFile(System.getProperty("user.dir")+"/topic.json");
Gson gson = new Gson();
Topic topic = gson.fromJson(jsonStr, Topic.class);
System.out.println(topic);
}
public static class RepresentativeStory{
String description,headline;
}
public static class Cluster{
public String clusterID;
public RepresentativeStory representativeStory;
}
public static class Topic {
String topicID;
String topicName;
boolean isMandatory;
List<Cluster> clusterList = new ArrayList<Cluster>();
ArrayList<String> clusterID = new ArrayList<String>();
@Override
public String toString() {
return new Gson().toJson(this);
}
}
}
文件 topic.json 包含您提供的 json 字符串。
为简洁起见,我在 RepresentativeStory 类中只定义了两个属性。您必须定义所有属性;这些类也被定义为内部类。
这是输出
{
"topicID": "512ecaf6e4b005fbcd13c681",
"topicName": "India",
"isMandatory": false,
"clusterList": [
{
"clusterID": "51c7d3e284ae6383d62480cc",
"representativeStory": {
"description": "NEW+DELHI%3A+Canadian+e-commerce+platform+provider%2C+Shopify+has+forayed+into+the+Indian+market+in+partnership+with+Singapore%27s+SingTel.+SingTel+will+help+build+ecosystem+which+includes+tying+up+with...",
"headline": "E-commerce+platform+provider+Shopify+enters+India"
}
},
{
"clusterID": "51c7d47784ae6383d624821c",
"representativeStory": {
"description": "MUMBAI%3A+Account+holders+in+rural+banks+and+small+cooperatives+can+now+make+online+purchases+with+the+National+Payment+Corporation+of+India+launching+an+e-commerce+solution+for+its+RuPay+card.+RuPay...",
"headline": "RuPay+cards+can+be+used+online"
}
},
{
"clusterID": "51c7d36d84ae6383d6247fc2",
"representativeStory": {
"description": "WASHINGTON%3A+Those+insidious+email+scams+known+as+phishing%2C+in+which+a+hacker+uses+a+disguised+address+to+get+an+internet+user+to+install+malware%2C+rose+87+per+cent+worldwide+in+the+past+year%2C+a...",
"headline": "Phishing+scams+rising+globally%3A+Study"
}
},
{
"clusterID": "51c7d62d84ae6383d6248366",
"representativeStory": {
"description": "With+India+making+it+clear+that+the+Afghan+reconciliation+process+should+not+lead+to+conferring+legitimacy+to+the+Taliban+and+undermine+the+elected+Afghan+government%2C+the+visiting+US+Secretary+of+Stat...",
"headline": "No+pact+if+Taliban+has+Qaeda+links%3A+Kerry"
}
},
{
"clusterID": "51c7d28084ae6383d6247e33",
"representativeStory": {
"description": "Palestinian+president+Mahmud+Abbas+on+Sunday+formally+accepted+the+resignation+of+his+newly-installed+prime+minister+Rami+Hamdallah....",
"headline": "President+Abbas+accepts+resignation+of+PM%3A+source"
}
},
{
"clusterID": "51c7d51a84ae6383d62482e1",
"representativeStory": {
"description": "With+land+being+acquired+in+Imphal%2C+Manipur+is+set+to+get+its+first+international+airport....",
"headline": "Eye+on+SE+Asia%2C+Manipur+set+to+get+first+international+airport"
}
},
{
"clusterID": "51c7d39184ae6383d624800e",
"representativeStory": {
"description": "The+state+government+may+declare+mangroves+as+%E2%80%9Creserved+forests%E2%80%9D.+Currently%2C+mangroves+on+government+land+are+deemed+%E2%80%9Cprotected+forests%E2%80%9D+while+those+on+private+land+are+%E2%80%9Cforests%E2%80%9D....",
"headline": "Mangroves+in+Maharashtra+may+get+status+of+%E2%80%98reserved+forests%E2%80%99"
}
},
{
"clusterID": "51c7d38084ae6383d6247fe8",
"representativeStory": {
"description": "NEW+DELHI%3A+Starting+June+21%2C+you+can+pay+your+passport+processing+fees+online+and+book+an+appointment+with+the+passport+office.+Making+passport+services+a+timely%2C+transparent%2C+more+accessible+and...",
"headline": "Now%2C+pay+pay+passport+fees+online"
}
}
],
"clusterID": [
"51c7d3e284ae6383d62480cc",
"51c7d47784ae6383d624821c",
"51c7d36d84ae6383d6247fc2",
"51c7d62d84ae6383d6248366",
"51c7d28084ae6383d6247e33",
"51c7d51a84ae6383d62482e1",
"51c7d39184ae6383d624800e",
"51c7d38084ae6383d6247fe8"
]
}
您可以根据您的确切需求即兴创作此代码!
关于Android JsonArray 和 JsonObject 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17403256/
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
首先,我使用的是rails3.1.3和来自master的carrierwavegithub仓库的分支。我使用after_init钩子(Hook)来确定基于属性的字段页面模型实例并为这些字段定义属性访问器将值存储在序列化哈希中(希望它清楚我是什么谈论)。这是我正在做的事情的精简版:classPage省略mount_uploader命令让我可以访问我想要的属性。但是当我安装uploader时出现错误消息说“nil类的未定义新方法”我在源代码中读到有方法read_uploader和扩展模块中的write_uploader。我如何必须覆盖这些来制作mount_uploader命令使用我的“虚拟
我有一个存储JSON数据的列。当它处于编辑状态时,我不知道如何显示它。serialize:value,JSON=f.fields_for:valuedo|ff|.form-group=ff.label:short=ff.text_field:short,class:'form-control'.form-group=ff.label:long=ff.text_field:long,class:'form-control' 最佳答案 代替=f.fields_for:valuedo|ff|请使用以下代码:=f.fields_for:va
在RubyonRails中,如果数组为空,则具有序列化数组字段的模型将不会在.save()上更新,而它之前有数据。我正在使用:ruby2.2.1rails4.2.1sqlite31.3.10我创建了一个字段设置为文本的新模型:railsgmodel用户名:stringexample:text在我添加的User.rb文件中:serialize:example,Array我实例化了User类的一个新实例:test=User.new然后我保存用户以确保它正确保存:test.save()(0.1ms)begintransactionSQL(0.4ms)INSERTINTO"users"("cr
是否可以在使用YAML.load_file时强制Ruby调用初始化方法?我想调用该方法以便为我不序列化的实例变量提供值。我知道我可以将代码分解成一个单独的方法并在调用YAML.load_file之后调用该方法,但我想知道是否有更优雅的方法来处理这个问题。 最佳答案 我认为你做不到。由于您要添加的代码确实特定于要反序列化的类,因此您应该考虑在类中添加该功能。例如,让Foo成为您要反序列化的类,您可以添加一个类方法,例如:classFoodefself.from_yaml(yaml)foo=YAML::load(yaml)#editth
我正在使用Ruby、Grape和ActiveRecord构建一个网络API。来自ASP.NETWebAPI我习惯于从JSON到类对象的自动模型绑定(bind),然后可以使用EntityFramework保存。我一直在搜索一下,看看在使用ActiveRecord时是否有类似的东西,但没有发现任何让我觉得我遗漏了一些非常明显的东西。将JSON反序列化为ActiveRecord模型的最佳方法是什么?更新Matts回答对简单类型非常有效,但是当我有关联时,我收到以下错误:ActiveRecord::AssociationTypeMismatch:Connector(#7029771166878
为什么Ruby的内置JSON不能反序列化简单的JSON原语,我该如何解决这个问题?irb(main):001:0>require'json'#=>trueirb(main):002:0>objects=[{},[],42,"",true,nil]#=>[{},[],42,"",true]irb(main):012:0>objects.eachdo|o|irb(main):013:1*json=o.to_jsonirb(main):014:1>beginirb(main):015:2*pJSON.parse(json)irb(main):016:2>rescueException=>ei
我试图在单个数据库字段中保存选项的散列。该表单能够将数据保存到数据库,但当我去编辑它时无法再次检索它(例如,除了wp_options字段之外,所有其他字段都已预填充)。classProfile这是我的自定义类:classWP_Optionsattr_accessor:wp_name,:wp_desc,:wp_limitend在我的表单中:true)do|f|%>......在我的Controller中:@profile=Profile.new(:wp_options=>WP_Options.new)在我的数据库列“wp_options”中:---!map:ActiveSupport::
根据ruby-doc和apidock,您可以使用to_json和json_create序列化和反序列化异常。但是在浪费了一些时间尝试使用它们之后,我仍然没有找到办法。调用exc.to_json给我一个空哈希,Exception.json_create(hash)给我这个错误:undefinedmethod'json_create'forException:类我想我可以很容易地重新创建这些函数,因为源代码可用,但我更愿意了解我做错了什么……有什么想法吗? 最佳答案 默认情况下,JSON模块不会扩展Exception。您必须要求“jso
编码和ActiveRecord序列化有什么区别?在将对象保存到数据库中时,是否有任何特定情况更适合使用其中一种方法? 最佳答案 国际研究中心:不保证RubyMarshall可以跨不同的ruby版本或不同平台上的相同ruby版本工作。因为您可能有不同的Ruby版本访问相同的序列化列,Rails使用YAML实现它的序列化。虽然速度较慢,但它确实保证您的序列化列可以被其他ruby版本、其他操作系统上的ruby以及其他编程语言读取。 关于ruby-on-rails-RubyO