如何从Java中的String获取JSON对象?

时间:2013-09-06 11:26:01

标签: java json string jsonobject

我是JSON的新手所以请原谅我的无知。我需要得到一个像这样的JSON对象:

jsonString =
{
    "Key": {"AppID":"19","Username":"sompoRoot","Password":"11223344"},
    "deviceList": ["43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6",
                   "43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6"],
    "aps": {"alert":"merhaba dunya","sound":"default","badge":"10",
    "dictionaryArray":["a","b"],
    "production":"false"}   
}

我将从数据库中获取AppID,用户名和密码。 deviceList是这样的:43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6,43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6 ...我会从文本输入中获得警报,声音,徽章字典和生产。我得到并转换String这些参数。我从互联网上搜索,但我认为它更复杂,我怎么能得到那样的JSON,谢谢。

4 个答案:

答案 0 :(得分:2)

您在评论中说,每个字段都有一个单独的字符串。我建议按以下方式构建包含所有所需字段的class(因为aps似乎是一个单独的实体,为它创建一个单独的类):

public class MyClass {
    private String key;
    private List<String> deviceList;
    private Aps aps;
}

public class Aps {
    private String alert;
    private String sound;
    private long badge;
    private List<String> dictionaryArray;
    private boolean production;
}

有几个库可以帮助您将Java对象转换为JSON,其中一个是Jackson's ObjectMapper class。您可以下载库from their website,或者如果您在项目中使用Maven,则可以找到mvnrepository.com的依赖项。

使用ObjectMapper

ObjectMapper objectMapper = new ObjectMapper();
MyClass myClass = new MyClass();
// .. populate the fields
String jsonString = objectMapper.writeValueAsString(myClass);

您必须将其包围在try-catch块中。就是这样:jsonString现在将您的字段转换为JSON字符串。


修改而不是杰克逊你可以使用Google GSON,它的工作方式大致相同。

答案 1 :(得分:2)

package com.stackoverflow.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

查看此link

答案 2 :(得分:1)

您可以使用Java的JSON库(GSON,Jettison等)。之后,在Map对象(嵌套结构)中添加数据,并使用库中的实用程序方法将其转换为JSON。

使用Jettison查找示例

   JSONObject json = new JSONObject();

   JSONObject jsonKey = new JSONObject();
   jsonKey.put("AppID", 19);
   jsonKey.put("Username", "usrname");
   jsonKey.put("Password", "passwd");


   String[] deviceList = {"value1", "value2"};

   json.put("key", jsonKey);
   json.put("deviceList", deviceList);

   String finalJson = json.toString();

答案 3 :(得分:0)

你可以尝试从google =的gson我认为这很简单快速 - &gt; https://code.google.com/p/google-gson/