遍历 JSON 字符串并获取键和值都要。

huangapple go评论75阅读模式
英文:

Iterate through JSON String and get Key and Value Both

问题

我有这个字符串,我想进行迭代:

{"First Name":"John","Last Name":"Doe"}

我希望获得键和值,因为键可以改变并且是动态的。

我尝试了许多方法来迭代并获取所有的键和值,但都没有成功。

英文:

I have this String that I want to Iterate Through:

{"First Name":"John","Last Name":"Doe"}

I want the Key and Value Both as the Keys can change and will be dynamic.

I have tried many ways to iterate and get all the keys and values but in vain.

答案1

得分: 1

你可以使用 jackson 库将你的字符串转换为一个映射:

        final String jsonString = "{\"First Name\":\"John\",\"Last Name\":\"Doe\"}";
        final Map<String, Object> jsonObject = new ObjectMapper().readValue(jsonString, Map.class);

然后你可以轻松地遍历键和它们的值。

英文:

You can use jackson library to convert your string to a map:

        final String jsonString = &quot;{\&quot;First Name\&quot;:\&quot;John\&quot;,\&quot;Last Name\&quot;:\&quot;Doe\&quot;}\&quot;&quot;;
        final Map&lt;String, Object&gt; jsonObject = new ObjectMapper().readValue(jsonString, Map.class);

Then you can easily iterate over keys and their values.

答案2

得分: 0

使用GsonTypeAdapter是其中的一个选项,它允许我假设是一个Person对象使用动态键进行编码和解码。

    static class Person {

        private final String firstName;

        private final String lastName;

        Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }
    }
   static class PersonTypeAdapter extends TypeAdapter<Person> {

        private final String firstNameKey;

        private final String lastNameKey;

        PersonTypeAdapter(String firstNameKey, String lastNameKey) {
            this.firstNameKey = firstNameKey;
            this.lastNameKey = lastNameKey;
        }

        @Override
        public void write(JsonWriter out, Person value) throws IOException {
            out.beginObject()
                    .name(firstNameKey).value(value.firstName)
                    .name(lastNameKey).value(value.lastName)
                    .endObject();
        }

        @Override
        public Person read(JsonReader in) throws IOException {
            in.beginObject();

            String firstNameValue = null;

            String lastNameValue = null;

            while (in.hasNext()) {
                String key = in.nextName();

                if (key.equals(firstNameKey)) {
                    firstNameValue = in.nextString();
                } else if (key.equals(lastNameKey)) {
                    lastNameValue = in.nextString();
                } else {
                    throw new UnsupportedOperationException("Unsupported key.");
                }
            }
            in.endObject();

            if (firstNameValue == null || lastNameValue == null) {
                throw new IllegalStateException("First name or last name is null.");
            }

            return new Person(firstNameValue, lastNameValue);
        }
    }
        String json = "{\"First Name\":\"John\",\"Last Name\":\"Doe\"}\n";

        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Person.class, new PersonTypeAdapter("First Name", "Last Name"))
                .create();

        Person person = gson.fromJson(json, Person.class);
Json result: com.Solution$Person@5f4da5c3[firstName=John,lastName=Doe]
英文:

One of many options is to use Gson with a TypeAdapter and allow what I assume is a Person object to be encoded and decoded with dynamic keys.

    static class Person {

        private final String firstName;

        private final String lastName;

        Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }
    }
   static class PersonTypeAdapter extends TypeAdapter&lt;Person&gt; {

        private final String firstNameKey;

        private final String lastNameKey;

        PersonTypeAdapter(String firstNameKey, String lastNameKey) {
            this.firstNameKey = firstNameKey;
            this.lastNameKey = lastNameKey;
        }

        @Override
        public void write(JsonWriter out, Person value) throws IOException {
            out.beginObject()
                    .name(firstNameKey).value(value.firstName)
                    .name(lastNameKey).value(value.lastName)
                    .endObject();
        }

        @Override
        public Person read(JsonReader in) throws IOException {
            in.beginObject();

            String firstNameValue = null;

            String lastNameValue = null;

            while (in.hasNext()) {
                String key = in.nextName();

                if (key.equals(firstNameKey)) {
                    firstNameValue = in.nextString();
                } else if (key.equals(lastNameKey)) {
                    lastNameValue = in.nextString();
                } else {
                    throw new UnsupportedOperationException(&quot;Unsupported key.&quot;);
                }
            }
            in.endObject();

            if (firstNameValue == null || lastNameValue == null) {
                throw new IllegalStateException(&quot;First name or last name is null.&quot;);
            }

            return new Person(firstNameValue, lastNameValue);
        }
    }
        String json = &quot;{\&quot;First Name\&quot;:\&quot;John\&quot;,\&quot;Last Name\&quot;:\&quot;Doe\&quot;}\n&quot; +
                &quot;\n&quot;;

        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Person.class, new PersonTypeAdapter(&quot;First Name&quot;, &quot;Last Name&quot;))
                .create();

        Person person = gson.fromJson(json, Person.class);
Json result: com.Solution$Person@5f4da5c3[firstName=John,lastName=Doe]

huangapple
  • 本文由 发表于 2020年7月23日 19:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63053303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定