java - 相当于 php json_encode 的 Java 是什么

标签 java php json

我正在 Java 中实现 api 调用,唯一提供的示例是 PHP,我的问题是 json_encode 的 java 等价物是什么,所以我们得到完全相同的输出。

    foreach($products_from_order as $item_id => $item)
    {
        $value[] = array(
            'product_sku'    =>$item['sku'],
            'product_name'   =>$item['name'],
            'product_desc'   =>$item['description'],
            'product_price'  =>$item['price'],
            'product_url'    =>$item['url'],
            'product_image'  => $item['image'],
        );
    }

    $apiData = array("merchant_id"       => $merchantId,
        "order_id"          => $orderId,
        "customer_name"     => $customerName,
        "customer_email"    => $customerEmail,
        "purchase_date"     => $purchaseDate,
        "products"          => $value,
        "key"               => $apiKey,
        "hmac"              => $calculatedHmac
    );
    $data_string = json_encode($apiData)

我现在有一个示例输出,所以我想我只需要知道在 java 中执行此操作的最简单方法

{
   "merchant_id":"526",
   "order_id":"15",
   "customer_name":"Tom Tester",
   "customer_email":"larry+tomtester@acompany.com",
   "purchase_date":"2017-01-27 22:05:56",
   "key":"24e694753d1c6d957882d4d560902b3f05454a0357b4c73a5bc66469653644cf9374ed5de8a2781d4151732299e821c4adf726f884923a46ae60a43d1b197164",
   "hmac":"kH9BBiRPMdHTP\\/dZgcUCPaldhpL9ttUw+lYl7LdB32Q=",
   "products":[
      {
         "product_sku":"47",
         "product_name":"HP LP3065",
         "product_desc":"\\r\\n\\tStop your co-workers in their tracks with the stunning new 30-inch diagonal HP LP3065 Flat Panel Monitor. This flagship monitor features best-in-class performance and presentation features on a huge wide-aspect screen while letting you work as comfortably as possible - you might even forget you're at the office\\r\\n..",
         "product_price":"100.0000",
         "product_url":"http:\\/\\/ts.oc-develop.com\\/index.php?route=product\\/product&product_id=47",
         "product_image":"http:\\/\\/ts.oc-develop.com\\/image\\/cache\\/catalog\\/demo\\/hp_1-500x500.jpg"
      },
      {
         "product_sku":"41",
         "product_name":"iMac",
         "product_desc":"\\r\\n\\tJust when you thought iMac had everything, now there\\u00b4s even more. More powerful Intel Core 2 Duo processors. And more memory standard. Combine this with Mac OS X Leopard and iLife \\u00b408, and it\\u00b4s more all-in-one than ever. iMac packs amazing performance into a stunningly slim space.\\r\\n..",
         "product_price":"100.0000",
         "product_url":"http:\\/\\/ts.oc-develop.com\\/index.php?route=product\\/product&product_id=41",
         "product_image":"http:\\/\\/ts.oc-develop.com\\/image\\/cache\\/catalog\\/demo\\/imac_1-500x500.jpg"
      },
      {
         "product_sku":"28",
         "product_name":"HTC Touch HD",
         "product_desc":"\\r\\n\\tHTC Touch - in High Definition. Watch music videos and streaming content in awe-inspiring high definition clarity for a mobile experience you never thought possible. Seductively sleek, the HTC Touch HD provides the next generation of mobile functionality, all at a simple touch. Fully integrated with Windows Mobile Professional 6.1, ultrafast 3.5G, GPS, 5MP camera, plus lots more - all delivered on a breathtakingly crisp 3.8" WVGA touchscreen - you can take control of your mobile world wi..",
         "product_price":"100.0000",
         "product_url":"http:\\/\\/ts.oc-develop.com\\/index.php?route=product\\/product&product_id=28",
         "product_image":"http:\\/\\/ts.oc-develop.com\\/image\\/cache\\/catalog\\/demo\\/htc_touch_hd_1-500x500.jpg"
      }
   ]
}

更新 所以我选择了 Gson 库

为订单和人员创建 POJO

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

public class Order
{
    private String merchantId;
    private String customerEmail;
    private String customerName;
    private String orderId;
    private String purchaseDate;
    private String key;
    private String hmac;
    private List<Product> products = new ArrayList();

    public String getCustomerEmail()
    {
        return customerEmail;
    }

    public void setCustomerEmail(String customerEmail)
    {
        this.customerEmail = customerEmail;
    }

    public String getCustomerName()
    {
        return customerName;
    }

    public void setCustomerName(String customerName)
    {
        this.customerName = customerName;
    }

    public String getOrderId()
    {
        return orderId;
    }

    public void setOrderId(String orderId)
    {
        this.orderId = orderId;
    }

    public String getPurchaseDate()
    {
        return purchaseDate;
    }

    public void setPurchaseDate(String purchaseDate)
    {
        this.purchaseDate = purchaseDate;
    }

    public String getMerchantId()
    {
        return merchantId;
    }

    public void setMerchantId(String merchantId)
    {
        this.merchantId = merchantId;
    }

    public String getKey()
    {
        return key;
    }

    public void setKey(String key)
    {
        this.key = key;
    }

    public String getHmac()
    {
        return hmac;
    }

    public void setHmac(String hmac)
    {
        this.hmac = hmac;
    }

    public List<Product> getProducts()
    {
        return products;
    }

    public void addProducts(Product product)
    {
        products.add(product);
    }
}


public class Product
{
    private String productSku;
    private String productName;
    private String productDescription;
    private String productPrice;
    private String productUrl;
    private String productImage;

    public String getProductSku()
    {
        return productSku;
    }

    public void setProductSku(String productSku)
    {
        this.productSku = productSku;
    }

    public String getProductName()
    {
        return productName;
    }

    public void setProductName(String productName)
    {
        this.productName = productName;
    }

    public String getProductDescription()
    {
        return productDescription;
    }

    public void setProductDescription(String productDescription)
    {
        this.productDescription = productDescription;
    }

    public String getProductPrice()
    {
        return productPrice;
    }

    public void setProductPrice(String productPrice)
    {
        this.productPrice = productPrice;
    }

    public String getProductUrl()
    {
        return productUrl;
    }

    public void setProductUrl(String productUrl)
    {
        this.productUrl = productUrl;
    }

    public String getProductImage()
    {
        return productImage;
    }

    public void setProductImage(String productImage)
    {
        this.productImage = productImage;
    }
}

然后按如下方式调用它:

Order order = new Order();
        order.setMerchantId(String.valueOf(526));
        order.setOrderId(String.valueOf(15));
        order.setCustomerName("Tom Tester");
        order.setCustomerEmail("larry+tomtester@trustspot.io");
        order.setPurchaseDate("2017-01-27 22:05:56");
        order.setHmac("kH9AAiRPMdHTP/dZgcUCPaldhpL9ttUw+lYl7LdB32Q=");

        Product p1 = new Product();
        p1.setProductSku(String.valueOf(47));
        p1.setProductName("HP LP3065");
        p1.setProductDescription("\r\nStop your co-workers in their tracks with the stunning new 30-inc");
        p1.setProductPrice("100.0000");
        p1.setProductUrl("http://ts.oc-develop.com/index.php?route=product/product&amp;product_id=47");
        p1.setProductImage("http://ts.oc-develop.com/image/cache/catalog/demo/hp_1-500x500.jpg");
        order.addProducts(p1);
        Product p2 = new Product();
        p2.setProductSku(String.valueOf(41));
        p2.setProductName("iMac");
        p2.setProductDescription("\r\nJust when you thought iMac had everything,");
        p2.setProductPrice("100.0000");
        p2.setProductUrl("http://ts.oc-develop.com/index.php?route=product/product&amp;product_id=41");
        p2.setProductImage("http://ts.oc-develop.com/image/cache/catalog/demo/imac_1-500x500.jpg");
        order.addProducts(p2);

        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setPrettyPrinting().create();
        System.out.println(gson.toJson(order));

给出输出

{
  "merchant_id": "526",
  "customer_email": "larry+tomtester@trustspot.io",
  "customer_name": "Tom Tester",
  "order_id": "15",
  "purchase_date": "2017-01-27 22:05:56",
  "hmac": "kH9AAiRPMdHTP/dZgcUCPaldhpL9ttUw+lYl7LdB32Q\u003d",
  "products": [
    {
      "product_sku": "47",
      "product_name": "HP LP3065",
      "product_description": "\r\nStop your co-workers in their tracks with the stunning new 30-inc",
      "product_price": "100.0000",
      "product_url": "http://ts.oc-develop.com/index.php?route\u003dproduct/product\u0026amp;product_id\u003d47",
      "product_image": "http://ts.oc-develop.com/image/cache/catalog/demo/hp_1-500x500.jpg"
    },
    {
      "product_sku": "41",
      "product_name": "iMac",
      "product_description": "\r\nJust when you thought iMac had everything,",
      "product_price": "100.0000",
      "product_url": "http://ts.oc-develop.com/index.php?route\u003dproduct/product\u0026amp;product_id\u003d41",
      "product_image": "http://ts.oc-develop.com/image/cache/catalog/demo/imac_1-500x500.jpg"
    }
  ]
}

现在只是想知道为什么他们要转义“/”,例如在 hmac 中,在 api 文档中没有提到是否这样做,但在示例 json 中显然有,这是由 json_encode 还是其他东西完成的,对我来说似乎没有必要。

逃逸只是由于他们复制并粘贴日志输出而引起的。由于这个问题非常具体,我将删除它,这对其他人来说似乎没什么用

最佳答案

Java 中没有等效的库,但您可以尝试使用一些第三方库,例如 GSON 或 org.json。*

关于java - 相当于 php json_encode 的 Java 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41899816/

相关文章:

php - CSS :nth-child() selector in a PHP constructed site

jquery - 如何获取这个复杂 JSON 对象中的 ISBN_10 标识符

java - 如何将随机字符串转换为整数以派生另一个整数,然后将它们转换为字符串以发送到 JSON 有效负载

java - 阻止用户在java扫描仪中输入数字?

java - 域对象和 Controller 类

java - Spring AOP和Spring JPA,要执行的Aspect

用于 symfony2 中功能测试的 PHPUnit DataProvider

java - 在Java中,如何使用循环实例化新对象,将它们存储在数组中,然后使用它们?

PHP OOP 属性常量用法

javascript - 将几个json传递给javascript