XilongPei / Openparts

MIT License
3 stars 1 forks source link

Turning a bean to Json in java #47

Closed XilongPei closed 6 years ago

XilongPei commented 6 years ago

把一个bean转成JSON格式,然后交给Elasticsearch去索引,方便查找。 https://stackoverflow.com/questions/11692303/turning-a-bean-to-json-in-java

If you use GSON, you can do this is one line as:

CourseKeyInfo courseKeyInfo = new CourseKeyInfo("This Works!", "101"); String json = new Gson().toJson(courseKeyInfo); System.out.println(json); for this to work

download GSON JAR Add to your project build path That's all and the result is:

{"courseKey":"This Works!","institutionID":"101"}

XilongPei commented 6 years ago

How to convert Json to Java object using Gson [duplicate] https://stackoverflow.com/questions/38636254/how-to-convert-json-to-java-object-using-gson

Gson gson = new Gson(); String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}"; User user= gson.fromJson(jsonInString, User.class);

XilongPei commented 6 years ago

通用的把一个bean放到Elasticsearch中的方法。 beanToElasticsearch(String className, Object object, "doc", String id) Elasticsearch PRE,索引名字的前缀。 index => databases type => table

XilongPei commented 6 years ago
    <!-- json -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
    </dependency>