How to convert jsonString to JSONObject in Java

2018-12-31 06:24发布

I have String variable called jsonString:

{"phonetype":"N95","cat":"WP"}

Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers...

16条回答
闭嘴吧你
2楼-- · 2018-12-31 07:04

String to JSON using Jackson with com.fasterxml.jackson.databind:

Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * Simple code exmpl
 */
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();
查看更多
牵手、夕阳
3楼-- · 2018-12-31 07:05

Using org.json library:

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
查看更多
路过你的时光
4楼-- · 2018-12-31 07:18

You can use google-gson. Details:

Object Examples

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serialization)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}

Note that you can not serialize objects with circular references since that will result in infinite recursion.

(Deserialization)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
==> obj2 is just like obj

Another example for Gson:

Gson is easy to learn and implement, you need to know is the following two methods:

-> toJson() – convert java object to JSON format

-> fromJson() – convert JSON into java object

import com.google.gson.Gson;

public class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";

  public static void main(String[] args) {
      TestObjectToJson obj = new TestObjectToJson();
      Gson gson = new Gson();

      //convert java object to JSON format
      String json = gson.toJson(obj);

      System.out.println(json);
  }

}

Output

{"data1":100,"data2":"hello"}

Resources:

Google Gson Project Home Page

Gson User Guide

Example

查看更多
冷夜・残月
5楼-- · 2018-12-31 07:18

For setting json single object to list ie

"locations":{

}

in to List<Location>

use

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

jackson.mapper-asl-1.9.7.jar

查看更多
登录 后发表回答