JSON List sets are converted into JSON objects

  • 2020-05-27 04:47:51
  • OfStack

1. Simply manually place key pairs into JSONObject, then into put to JSONArray objects


 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();
   }

The above code JSONArray is the introduced org.json.JSONArray package

net. sf. json package JSONArray static method: fromObject(list) this is the web is most of the direct use of this method to quickly convert JSON, but for the Hibernate cascading operation associated with the object, this method will report an error, if you remove the cascading configuration in the mapping file.

In addition, the requirement for list is that the elements are strings or objects, otherwise JSON does not know what data you want.


<many-to-one name="cmsent" column="comment_tid" class="com.fcms.cms.entity.CmsComment" 
  not-null="false" cascade="delete">

But the cascade operation still has to exist after all, otherwise later data redundancy, redundant.

The solution is: 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;
     }
   }
  });

Note: provides a filter function, if the encounter of the associated object when he will automatically filter out, do not perform the association association of the associated object. Here I post my code for configuring relational mapping in hibernate to help you understand:


<!--  Configure the relationship between the topic and the group  -->
  <many-to-one name="article" class="com.fcms.nubb.article" column="article_id"/>
  
  <!--  Configure the relationship between the topic post and the replied post  -->
  <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>

Conclusion:

1. JSONArray subMsgs = JSONArray.fromObject(subMessages, config); Where config is optional, config parameter can be configured when the above situation occurs. If there is no such requirement as above, fromObject(obj) method can be directly used. What it converts is the data in the standard json object format, as follows:

{["attr", "content", ...}, ...]}

2. JSONObject jTmsg = JSONObject. fromObject(themeMessage, config); This is specifically used to parse standard pojo, or map objects, pojo objects, not to mention map objects in the form of {"str", "str"}.

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- division -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

For JSONArray and JSON used before want to vomit!!

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));
  }
  
}

Output:


[{"address":"address","age":11,"name":"amao"},{"address":"address","age":11,"name":"amao"}]


Related articles: