简体   繁体   English

在 Java 中实现 JSON 对象

[英]Implementing a JSON Object in java

orderHDRObjectList contains hdrObject table deatils and orderDETObjList contains orderDetails table list this is a valid jason and i want to implement this. orderHDRObjectList 包含 hdrObject 表详细信息,而 orderDETObjList 包含 orderDetails 表列表,这是一个有效的 jason,我想实现这一点。

and display orderHdrObjList of orderId=1 and corresponding orderDETObjList of orderId=1 and so on..并显示 orderId=1 的 orderHdrObjList 和 orderId=1 的对应 orderDETObjList 等等..

how can I do that?我怎样才能做到这一点?

{
    "orderObj": {
        "orderHDRObjList": {
            "hdrObject": [{
                    "orderID": 1,
                    "customerName": "Alex",
                    "address": "Kottayam",
                    "totalPrice": 250,
                    "orderDate": "2020-11-21"
                },
                {
                    "orderID": 2,
                    "customerName": "Aljin",
                    "address": "Kochi",
                    "totalPrice": 250,
                    "orderDate": "2020-11-21"
                }
            ]
        },
        "orderDETObjList": {
            "1": [{
                    "productId": 2,
                    "productQty": 250,
                    "price": 500
                },
                {
                    "productId": 3,
                    "productQty": 150,
                    "price": 300
                }
            ],
            "2": [{
                    "productId": 2,
                    "productQty": 250,
                    "price": 500
                },
                {
                    "productId": 3,
                    "productQty": 150,
                    "price": 300
                }
            ]
        }
    }
}

solution 1: use jackson explained here for converting your model to json: Converting Java objects to JSON with Jackson解决方案 1:使用此处解释的 jackson 将您的模型转换为 json: Converting Java objects to JSON with Jackson

solution 2: use java classes: JSONObject and JSONArray解决方案2:使用java类: JSONObjectJSONArray

*needs *需要

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

eg:例如:

JSONObject json = new JSONObject();
json.put("key1", "value1");

JSONArray array = new JSONArray();
array.put(1);
array.put(2);

json.put("numbers", array);

the output will be this输出将是这个

{
    "key1": "value1",
    "numbers": [
        1,
        2
    ]
}

to convert your java json object to a string use toString() method使用toString()方法将您的 java json 对象转换为字符串

System.out.println(json.toString());

some IDEs like IntelliJ suggests to put your json codes inside a try...catch because it may produce some Exceptions when you want to read data with a wrong index.一些像 IntelliJ 这样的 IDE 建议将您的 json 代码放在try...catch因为当您想要读取带有错误索引的数据时,它可能会产生一些异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM