
hashmap 基于数组加链表结构保存数据,遍历时,基本上可以视为通过hashCode遍历。
但是有特殊两点:
①:如果初始化hashmap时,指定的hash桶数量(小于16)如果不一致,那么 (n-1)&hash 所得的数组下标不一致。遍历的顺序将改变
②:发生hash冲突,同时,冲突的链表长度小于9. hash桶容量大于64; 此时按照链表存储,这部分数据遍历可能基于插入的顺序。(待验证)
例①:
HashMap map1 =new HashMap<>()
map1.put("123", "aaa")
map1.put("23456", "bbb")
System.out.println("map1的循环遍历")
for (Map.Entry entry : map1.entrySet()) {
System.out.println(entry.getKey())
}
HashMap map2 =new HashMap<>(map1.size())
map2.put("123", "aaa")
map2.put("23456", "bbb")
System.out.println("map2的循环遍历")
for (Map.Entry entry : map2.entrySet()) {
System.out.println(entry.getKey())
}
回到第二个问题:fastJson.toJson() 基于以上两点隐患,无法保证有序 JSONObject是基于Map.entrySet()遍历Map,而entrySet通过桶0节点循环遍历数组、链表,此时的数据并不能保证完全一致
1. 简单的手动放置 键值对 到JSONObject,然后在put到JSONArray对象里List<Article>al = articleMng.find(f)
System.out.println(al.size())
HttpServletResponse hsr = ServletActionContext.getResponse()
if(null == al){
return
}
for(Article a : al){
System.out.println(a.getId()+a.getDescription()+a.getTitle())
}
JSONArray json = new JSONArray()
for(Article a : al){
JSONObject jo = new JSONObject()
jo.put("id", a.getId())
jo.put("title", a.getTitle())
jo.put("desc", a.getDescription())
json.put(jo)
}
try {
System.out.println(json.toString())
hsr.setCharacterEncoding("UTF-8")
hsr.getWriter().write(json.toString())
} catch (IOException e) {
e.printStackTrace()
}
上述代码JSONArray是引入的org.json.JSONArray包
而用net.sf.json包下JSONArray的静态方法:fromObject(list) 这是网上大多是都是直接用此方法快捷转换JSON,但是对于Hibernate级联 *** 作关联的对象,这个方法就会报错,如果将映射文件中的级联配置去掉就行了。
另外对于list的要求就是其中的元素是字符串或对象,否则JSON不知道你想要的是什么数据。
<many-to-one name="cmsent" column="comment_tid" class="com.fcms.cms.entity.CmsComment"
not-null="false" cascade="delete">
但是级联 *** 作毕竟还是得存在,否则以后数据冗余、多余。
解决方法就是:JSONArray subMsgs = JSONArray.fromObject(object, config)
JsonConfig config = new JsonConfig()
config.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object arg0, String arg1, Object arg2) {
if (arg1.equals("article") ||arg1.equals("fans")) {
return true
} else {
return false
}
}
})
说明:提供了一个过滤作用,如果遇到关联的对象时他会自动过滤掉,不去执行关联关联所关联的对象。这里我贴出我hibernate中的配置关系映射的代码帮助理解:
<!-- 配置话题和团体之间的关系 -->
<many-to-one name="article" class="com.fcms.nubb.article" column="article_id"/>
<!-- 配置主题帖与回复的帖子之间的关系 -->
<set name="subMessages" table="sub_message" inverse="true" cascade="all" lazy="false" order-by="date asc">
<key column="theme_id" />
<one-to-many class="bbs.po.SubMessage" />
</set>
总结:
1. JSONArray subMsgs = JSONArray.fromObject(subMessages, config)其中config是可选的,当出现上面的情况是可以配置config参数,如果没有上面的那种需求就可以直接使用fromObject(obj)方法,它转换出来的就是标准的json对象格式的数据,如下:
{["attr", "content", ...}, ...]}
2. JSONObject jTmsg = JSONObject.fromObject(themeMessage, config)这是专门用来解析标准的pojo,或者map对象的,pojo对象的格式就不用说了,map的形式是这样的{"str", "str"}。
----------------------------------------------------------- 分割 -------------------------------------------------------------------------------------------
对于JSONArray和JSON之前用到想吐了!!!
但是,最近发现个好东西--fastjson (阿里巴巴温少写的一个将Object转为json数据的工具包)
Binary : http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1.jar
Source :http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1-sources.jar
Subversion : http://code.alibabatech.com/svn/fastjson/
bean
package com.nubb.bean
import java.io.Serializable
public class Person implements Serializable{
private static final long serialVersionUID = 1L
private String name
private int age
private String address
public String getName() {
return name
}
public void setName(String name) {
this.name = name
}
public int getAge() {
return age
}
public void setAge(int age) {
this.age = age
}
public String getAddress() {
return address
}
public void setAddress(String address) {
this.address = address
}
}
JsonUtil
package com.nubb.test
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.ArrayList
import java.util.List
import com.alibaba.fastjson.JSON
import com.nubb.bean.Person
public class JSONSerializer {
private static final String DEFAULT_CHARSET_NAME = "UTF-8"
public static <T>String serialize(T object) {
return JSON.toJSONString(object)
}
public static <T>T deserialize(String string, Class<T>clz) {
return JSON.parseObject(string, clz)
}
public static <T>T load(Path path, Class<T>clz) throws IOException {
return deserialize(
new String(Files.readAllBytes(path), DEFAULT_CHARSET_NAME), clz)
}
public static <T>void save(Path path, T object) throws IOException {
if (Files.notExists(path.getParent())) {
Files.createDirectories(path.getParent())
}
Files.write(path,
serialize(object).getBytes(DEFAULT_CHARSET_NAME),
StandardOpenOption.WRITE,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING)
}
public static void main(String[] args) {
Person person1 = new Person()
person1.setAddress("address")
person1.setAge(11)
person1.setName("amao")
Person person2 = new Person()
person2.setAddress("address")
person2.setAge(11)
person2.setName("amao")
List<Person>lp = new ArrayList<Person>()
lp.add(person1)
lp.add(person2)
System.out.println(serialize(lp))
}
}
输出:
[{"address":"address","age":11,"name":"amao"},{"address":"address","age":11,"name":"amao"}]
这个可以使用for循环加上java的Map集合来做, 代码冗长,扩展性差,不推荐!!
推荐使用 阿里的fastjson.jar包 或者gson来处理 因为你提供的数据都是JSON格式的数据
以fastjson为例,参考代码如下
//使用fastjson包import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
public class Test {
public static void main(String[] args) {
//json字符串
String jsonStr = "[{'a':1,'b':3,'c':5},{'a':1,'b':7,'c':9},{'a':2,'b':2,'c':3},{'a':1,'b':2,'c':3},{'a':2,'b':4,'c':5}]"
JSONArray objects = JSON.parseArray(jsonStr)//字符串-->json数组
JSONArray oneAry=new JSONArray()//json数组
JSONArray twoAry=new JSONArray()//json数组
for (int i = 0 i < objects.size() i++) {
JSONObject obj = (JSONObject) objects.get(i)
int avlue = (int) obj.get("a")//获取a的值
if(avlue==1){//如果是1,那么存入数组1
oneAry.add(obj)
}else if(avlue==2){
twoAry.add(obj)
}
}
JSONObject one=new JSONObject()
one.put("one", oneAry)//存入到json对象
JSONObject two=new JSONObject()
two.put("two", twoAry)
System.out.println(one)
System.out.println(two)
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)