什么是Java相当于php json_encode

时间:2017-01-27 17:35:07

标签: 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或其他东西完成的,它对我来说似乎没有必要。

逃脱只是由他们复制和粘贴日志输出引起的。由于这个问题已经相当具体我要删除它似乎对任何人都没用

2 个答案:

答案 0 :(得分:0)

Java中没有相应的内容,但您可以尝试使用GSON或org.json等第三方库。*

答案 1 :(得分:0)

如果结果对象保持为&#34;平坦&#34;在你的例子中,你可以考虑自己构建对象,我也曾多次这样做以避免使用外部库。只需循环遍历数组并填充例如字段。一个字符串。