当前位置: 首页 > 知识库问答 >
问题:

JSON字符串到Java字符串

焦正德
2023-03-14

我有以下JSON字符串:

{
    "Results": {
        "output1": {
            "type": "table",
            "value": {
                "ColumnNames": ["userId", "documentId", "Scored Labels", "Scored Probabilities"],
                "ColumnTypes": ["String", "String", "Boolean", "Double"],
                "Values": [["100213199594809000000", "1Ktol-SWvAh8pnHG2O7HdPrfbEVZWX3Vf2YIPYXA_8gI", "False", "0.375048756599426"], ["103097844766994000000", "1jYsTPJH8gaIiATix9x34Ekcj31ifJMkPNb0RmxnuGxs", "True", "0.753859758377075"]]
            }
        }
    }
}

我只想要列名。我试过这样的方法:

Map<String,Object> map = mapper.readValue(filename, Map.class);
String CN = (String) map.get("ColumnNames");

但我得到了以下错误:

Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@64232b15; line: 1, column: 2]`

我只使用过几次JSON。有人能帮我吗?

对我来说最好的例子是这样的,我在另一个例子中做过:

String uId = (String) attr.get("userId");

可能吗?

现在我已经做到了:

我试着这样做:

public class ClientPOJO {

    private String userId;
    private String documentId;


    public String getuserId() {
        return userId;
    }

    public void setuserId(String userId) {
        this.userId = userId;
    }

    public String getdocumentId() {
        return documentId;
    }

    public void setdocumentId(String documentId) {
        this.documentId = documentId;
    }

}

然后:

ObjectMapper mapper = new ObjectMapper();
                    ClientPOJO clientes= mapper.readValue(filename, ClientPOJO.class);

String uid = clientes.getuserId();

但现在当我做一个Prtinout时,我会得到和以前一样的错误:

    Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: java.io.StringReader@7a6eb29d; line: 1, column: 2]

共有3个答案

夏飞鹏
2023-03-14

如果您确切知道json的结构(比如您发布的json),那么您可以使用Gson获得如下对象:

JsonParser parser = new JsonParser();
JsonObject json = (JsonObject) parser.parse("your_json_string_here");
String column = json.get("Results").getAsJsonObject().get("output1").getAsJsonObject().get("value").getAsJsonObject().get("ColumnNames").getAsJsonArray().toString();
String value = json.get("Results").getAsJsonObject().get("output1").getAsJsonObject().get("value").getAsJsonObject().get("Values").getAsJsonArray().toString();    
System.out.println(column);
System.out.println(value);

如果您需要一些更通用的东西,那么可以将json字符串解析为HashMap

Type type = new TypeToken<HashMap<String, Object>>() {}.getType();
Gson gson = new Gson();
HashMap<String, Object> map = gson.fromJson("your_json_string_here", type);
    for (String key : map.keySet()) {
        Object obj = map.get(key);
        if (obj instanceof List) {
            for (Object o : (List) obj) {
                if (o instanceof Map) {
                    loop((Map) o);
                } else {
                    System.out.println(key + " : " + o);
                }
            }
        } else if (obj instanceof Map) {
            loop((Map) obj);
        } else {
            System.out.println(key + " : " + obj);
        }
    }
}

private static void loop(Map<String, Object> map) {
    for (String key : map.keySet()) {
        Object obj = map.get(key);
        if (obj instanceof List) {
            for (Object o : (List) obj) {
                if (o instanceof Map) {
                    loop((Map) o);
                } else {
                    System.out.println(key + " : " + o);
                }
            }
        } else if (obj instanceof Map) {
            loop((Map) obj);
        } else {
            System.out.println(key + " : " + obj);
        }
    }
}

裴金鑫
2023-03-14

下面是一个例子来说明解决问题的通用方法(基于Jackson library)。您可能希望增强解决方案以满足您的所有需求。

内联评论。

package com.stackoverflow;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

// Junit class
public class TableDeserExample {
    // sample input
    String inputJson = "{\n" +
            "    \"Results\": {\n" +
            "        \"output1\": {\n" +
            "            \"type\": \"table\",\n" +
            "            \"value\": {\n" +
            "                \"ColumnNames\": [\"userId\", \"documentId\", \"Scored Labels\", \"Scored Probabilities\"],\n" +
            "                \"ColumnTypes\": [\"String\", \"String\", \"Boolean\", \"Double\"],\n" +
            "                \"Values\": [[\"100213199594809000000\", \"1Ktol-SWvAh8pnHG2O7HdPrfbEVZWX3Vf2YIPYXA_8gI\", \"False\", \"0.375048756599426\"], [\"103097844766994000000\", \"1jYsTPJH8gaIiATix9x34Ekcj31ifJMkPNb0RmxnuGxs\", \"True\", \"0.753859758377075\"]]\n"
            +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}";

    // POJO to map the Json structure. You may want to make it generalize based
    // on field "type"
    // (https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization)
    public static class Result {
        private String type;
        private TableResult value;

        public String getType() {
            return this.type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public void setValue(TableResult value) {
            this.value = value;
        }

        public TableResult getValue() {
            return this.value;
        }
    }

    // Pojo for table result
    public static class TableResult {
        private List<String> columnNames;
        private List<String> columnTypes;
        private List<Object[]> values;

        @JsonProperty("ColumnNames")
        public List<String> getColumnNames() {
            return this.columnNames;
        }

        public void setColumnNames(List<String> columnNames) {
            this.columnNames = columnNames;
        }

        @JsonProperty("ColumnTypes")
        public List<String> getColumnTypes() {
            return this.columnTypes;
        }

        public void setColumnTypes(List<String> columnTypes) {
            this.columnTypes = columnTypes;
        }

        @JsonProperty("Values")
        public List<Object[]> getValues() {
            return this.values;
        }

        public void setValues(List<Object[]> values) {
            this.values = values;
        }

    }

    // Top level Json POJO
    public static class ResultContainer {
        private Map<String, Result> results;

        @JsonProperty("Results")
        public Map<String, Result> getResults() {
            return this.results;
        }

        public void setResults(Map<String, Result> results) {
            this.results = results;
        }
    }

    // A contract to map the result "values" to the expected object
    public static interface ResultMapper<T> {
        T map(TableResult map, Object[] row);
    }

    // Basic implementation for mapping user object from json "values[i]" array
    public static class UserTableResultMapper implements ResultMapper<User> {

        @Override
        public User map(TableResult result, Object[] row) {
            User user = new User();
            // Here use any mapper logic based on column name
            // Retrieved from result object.
            // Below are for illustration only
            user.setId(String.valueOf(row[0]));
            user.setDocumentId(String.valueOf(row[1]));
            return user;
        }

    }

    // A result reader class
    public static class ResultReader<T> implements Iterable<T> {
        private TableResult result;
        private ResultMapper<T> mapper;

        public ResultReader(TableResult result, ResultMapper<T> mapper) {
            this.result = result;
            this.mapper = mapper;
        }

        @Override
        public Iterator<T> iterator() {
            final Iterator<Object[]> itr = result.getValues().iterator();
            return new Iterator<T>() {

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

                @Override
                public T next() {
                    Object[] values = itr.next();
                    return mapper.map(result, values);
                }

                @Override
                public boolean hasNext() {
                    return itr.hasNext();
                }
            };
        };
    }

    public static class User {
        private String id;
        private String documentId;
        // and others

        public String getId() {
            return this.id;
        }

        public void setDocumentId(String documentId) {
            this.documentId = documentId;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getDocumentId() {
            return this.documentId;
        }

    }

    @Test
    public void simpleTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        ResultContainer file = mapper.readValue(inputJson, ResultContainer.class);
        Result result = file.getResults().get("output1");
        ResultReader<User> userResultReader = new ResultReader<>(result.getValue(), new UserTableResultMapper());
        for (User user : userResultReader) {
            System.out.println(user.getId() + " : " + user.getDocumentId());
        }
    }
}
东方建修
2023-03-14

Java-将JSON字符串转换为字符串/整数/对象

String jsonString = "{"username":"Gajender"}";
org.json.JSONObject jsonObj =new JSONObject(jsonString);
String name = (String) jsonObj.get("username").toString();
 类似资料:
  • 问题内容: 我在Java程序中有两个字符串,我想以某种方式混合以形成两个新字符串。为此,我必须从每个字符串中提取一些构成字符并将其添加以形成新的字符串。我有这样的代码(this.eka和this.toka是原始字符串): 我正在获取.charAt(x)部分的数字,那么如何将字符转换为字符串? 问题答案: 只使用永远使用代替 例如,当位置arent不是固定值而变量 其中x,y,z是保存从中提取位置的

  • 问题内容: 我有以下要发送到NodeJS服务器的JSON字符串: 当字符串包含字符和 在NodeJS服务器上,我正在像这样解析JSON: 有什么想法我可以设法毫无问题地发送所有字符吗? 问题答案: 我会使用一个库来为您创建JSON 。一些选项是: GSON 克罗福德的解放 这将使转义变得更加容易。一个示例(使用)为:

  • 我有Json String看起来像这样 并希望将此Json字符串转换为对象的数组列表,并将所有元素放在类(数据Object.class)上并打印元素。 输出为: 我创建的类具有这种形式 我做错了什么?

  • 问题内容: 我正在尝试用Java创建一个简单的String to SHA1转换器,这就是我所拥有的… 当我通过它时,我[.知道它可能是像UTF-8这样的简单编码修复程序,但是有人可以告诉我我应该怎么做才能得到我想要的东西吗?还是我这样做完全错误? 问题答案: 这是我将字符串转换为sha1的解决方案。它在我的Android应用程序中运行良好:

  • 问题内容: 我有一个Java属性文件,并且有一个as 。因此,在加载如下所示的属性文件后,我使用方法检索的:: 然后 我需要从上面的字符串创建一个HashMap。应该是HashMap中,并应第秒。 如果是硬连线的,则如下所示: 问题答案: 将该方法与分隔符一起使用,以获取对列表。迭代对,然后再次使用分隔符以获取每个对的键和值。

  • 我必须将java“转换”为c。我做得对吗?你能纠正吗 爪哇-