简体   繁体   中英

What is the Java equivalent to php json_encode

I am implementing an api call in Java, the only example provided is in PHP, my question what is the java equivalent of json_encode so we get exactly the same output.

    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)

I now have an example output so I suppose I just need to know the easiest way to do this in 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"
      }
   ]
}

Update So I went with the Gson library

Create a POJO for Order and Person

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

and then called it as follows:

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

Gave the output

{
  "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"
    }
  ]
}

Now just wondering why they have escaped '/' such as in hmac, there is no mention if doing this in the api document, but it is clearly there in the example json, is this done by json_encode or something else, it doesn't seem necessary to me.

The escapes were just caused by them copying and pasting their log output. Since this question has got rather specific Im going to delete it doesnt seem that useful to anyone else

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

If the result object stays as "flat" as in your example, you could consider constructing the object yourself, which I also did on several occasions to avoid external libraries. Just loop through the array and fill the fields in eg a String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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