You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Moshi解析含嵌套数组的JSON字符串并映射至实体类

Hey there! Let's figure out how to parse that JSON string with your existing Structure class using Moshi. Here's a step-by-step breakdown:

1. Update the Entity Class to Match the JSON

First, your current Structure class is missing the categories field present in the JSON. We need to add that, plus a helper class to map each fruit entry in the array. Since the JSON uses a key with a space ("fruit name"), we'll use Moshi's @Json annotation to link it to a Java-friendly field name:

import com.squareup.moshi.Json;
import java.util.List;

class Structure {
    String user;
    String password;
    String store;
    List<Fruit> categories; // Added field to match the JSON array

    // Your existing private constructor
    private Structure() {
        this.user = "sam";
        this.password = "abcd1234";
        this.store = "SPROUTS";
    }

    // Inner class to map individual fruit objects from the JSON array
    static class Fruit {
        @Json(name = "fruit name") // Maps the spaced JSON key to this field
        String fruitName;
    }
}

2. Handle the Private Constructor

Moshi can work with private constructors out of the box using reflection (as long as you're using the default Moshi instance). When parsing, it will first call your private constructor to create an instance, then overwrite the fields with values from the JSON. If you prefer to avoid reflection or want explicit control over object creation, add a public constructor annotated with @JsonCreator:

@JsonCreator
public Structure(
        @Json(name = "user") String user,
        @Json(name = "password") String password,
        @Json(name = "store") String store,
        @Json(name = "categories") List<Fruit> categories) {
    this.user = user;
    this.password = password;
    this.store = store;
    this.categories = categories;
}

This tells Moshi to use this constructor directly instead of relying on reflection.

3. Write the Parsing Logic

Now let's put it all together to parse the JSON string:

import com.squareup.moshi.Moshi;
import java.io.IOException;

public class JsonParserExample {
    public static void main(String[] args) {
        // Your target JSON string
        String json = "{ \"user\": \"sam\", \"password\": \"abcd1234\", \"categories\": [ { \"fruit name\": \"watermelon\" }, { \"fruit name\":\"jackfruit\" }, { \"fruit name\": \"kiwi\" } ], \"store\":\"SPROUTS\" }";

        // Create a Moshi instance
        Moshi moshi = new Moshi.Builder().build();

        // Get the adapter for the Structure class
        JsonAdapter<Structure> structureAdapter = moshi.adapter(Structure.class);

        try {
            // Parse the JSON into a Structure object
            Structure structure = structureAdapter.fromJson(json);

            // Verify the result by printing the fruit names
            if (structure != null && structure.categories != null) {
                for (Structure.Fruit fruit : structure.categories) {
                    System.out.println("Fruit: " + fruit.fruitName);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. Add Moshi Dependency

Don't forget to include Moshi in your project. For Gradle, add this to your module-level build.gradle:

implementation 'com.squareup.moshi:moshi:1.14.0'

That's all! This setup will correctly parse your JSON into the Structure object, including the list of fruits from the categories array.

内容的提问来源于stack exchange,提问作者SinSri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:44:33