Total Pageviews

Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

2017/09/04

[JSON] Using JSONObject to build and parse JSON

Assume we would like to build a user JSON string, it looks like:
{"users":[{"name":"Albert","id":1},{"name":"Mandy","id":2}]}

Steps:
1. Create a User object which have two attributes (id and name)
2.  Create a getUsers method to retrieve dummy user collection 
3. Create buildUserJson() to build JSON string from List of User 
package albert.practice.json;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonObjectTest {

    public static void main(String[] args) {

        JsonObjectTest test = new JsonObjectTest();
        
        String userJSON = test.buildUserJson();
        log.debug("user JSON = " + userJSON);
    }

    public String buildUserJson() {
        List<User> users = getUsers();
        JSONObject dataset = new JSONObject();
        users.stream().forEach(u -> addToDataset(u, dataset));

        return dataset.toString();
    }

    private static void addToDataset(User user, JSONObject dataset) {
        JSONObject userObj = new JSONObject();
        userObj.put("id", user.getId());
        userObj.put("name", user.getName());

        // use the accumulate function to add to an existing value. The value
        // will now be converted to a list
        dataset.accumulate("users", userObj);
    }

    public List<User> getUsers() {
        User albert = new User(1, "Albert");
        User mandy = new User(2, "Mandy");
        return Arrays.asList(albert, mandy);
    }

    @Data
    @AllArgsConstructor
    @ToString
    private static class User {
        private Integer id;
        private String name;
    }

}


If you would like to parse JSON string to List of User, you can check parseUserJson(String json)
    public List<User> parseUserJson(String json) {
        JSONObject jsonObj = new JSONObject(json);
        JSONArray userArray = (JSONArray) jsonObj.get("users");

        List<User> users = new ArrayList<>();

        userArray.forEach(u -> addToList(u, users));

        return users;
    }

    private void addToList(Object user, List<User> users) {
        JSONObject userObj = (JSONObject) user;
        Integer id = (Integer) userObj.get("id");
        String name = (String) userObj.get("name");
        users.add(new User(id, name));
    }




Reference
[1] http://www.studytrails.com/java/json/java-org-json.jsp

2011/09/17

net.sf.json.JSONException: org.apache.openjpa.lib.util.ParseException

Scenario
當使用者輸入異常代號,系統要自動帶出違章編號徵銷管理代號應納金額已納金額等欄位。

 


Problem
在Controller,我們會去呼叫後端service class,根據使用者所輸入的異常代號進行搜尋,帶回符合條件的entity(i.e. NIGT900),但是在轉成JSONObject的時候,出現下列錯誤訊息:
net.sf.json.JSONException: org.apache.openjpa.lib.util.ParseException: Errors occurred while creating property descriptors for the following properties: [RefreshFromDataCache, CacheMarshallers, jdbc.QuerySQLCache, jdbc.CollectionId, AccessIntent].
at net.sf.json.JSONObject._fromBean(JSONObject.java:987) ~[json-lib-2.3-jdk15.jar:na]


Root Cause
由於回傳的entity(i.e. NIGT900)有一個資料型態為Timestamp的欄位,導致會出現此錯誤



Solution
利用JsonConfig將timeStamp欄位exclude掉

Result



2011/09/08

net.sf.json.JSONException: There is a cycle in the hierarchy!


Problem
I apply JPA(Java Persistence API) to do search via primary key, then it return an object to me. And I would like to covert this object to JSONObject, it show this error message.

1
2
3
4
5
6
7
net.sf.json.JSONException: There is a cycle in the hierarchy! 
at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97) 
at net.sf.json.JSONObject._fromBean(JSONObject.java:674)
at net.sf.json.JSONObject.fromObject(JSONObject.java:181) 
at net.sf.json.JSONArray._processValue(JSONArray.java:2381) 
at net.sf.json.JSONArray.processValue(JSONArray.java:2412) Truncated. 
see log file for complete stacktrace


The code snippet as shown below


Root Cause
Because the entity you return has many-to-one relationship, so you need to filter them out.

Solution



Reference: http://json-lib.sourceforge.net/snippets.html