Created
June 6, 2014 05:58
-
-
Save tos-kamiya/5e68c9bab9982090d1b0 to your computer and use it in GitHub Desktop.
Gsonの使い方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gsonshow; | |
import java.io.IOException; | |
import java.nio.charset.StandardCharsets; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import com.google.gson.Gson; | |
public class GsonShow { | |
public static void main(String[] args) throws IOException { | |
Order o1 = new Order("かき氷シロップ", 1, 300); | |
Order o2 = new Order("かき氷シロップ", 2, 300); | |
Order o3 = new Order("かき氷シロップ", 1, 310); | |
Order o4 = new Order("かき氷シロップ いちご", 1, 300); | |
Gson gson = new Gson(); | |
System.out.println(gson.toJson(o1)); | |
String s = "{\"product\":\"スイカ\",\"count\":1,\"price\":1000}"; | |
Order o5 = gson.fromJson(s, Order.class); | |
System.out.println(o5); | |
byte[] bytes = Files.readAllBytes(Paths.get("datafile.json")); | |
String datafileStr = new String(bytes, StandardCharsets.UTF_8); | |
Order[] o6 = gson.fromJson(datafileStr, Order[].class); | |
System.out.println(o6); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gsonshow; | |
public class Order { | |
private String product; | |
private int count; | |
private int price; | |
public Order(String product, int count, int price) { | |
this.product = product; | |
this.count = count; | |
this.price = price; | |
} | |
public String getProduct() { | |
return product; | |
} | |
public int getCount() { | |
return count; | |
} | |
public int getPrice() { | |
return price; | |
} | |
@Override | |
public String toString() { | |
return String.format("Order(%s,%d,%d)", product, count, price); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment