GSON库:无法将JSON元素的数组解析为Java对象的String[]

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

GSON lib: cant parse JSON element's array to String[] of Java object

问题

我导入了最新版本的GSON库。
下面的Java程序控制台显示"null",但当我尝试打印对象的其他属性时,一切正常。这意味着GSON函数可以将JSON元素解析为Java对象,但无法处理muscle_groups属性,因此String[]返回null。
我尝试过更改Java数据类型,还向Chat GPT提问,但仍然无法解决。
我不知道如何修复这个问题...

Java对象类:

import java.util.ArrayList;
import java.util.List;

public class WorkoutExercises {
    String name, description, time, level, goal;
    int id;
    List<String> muscleGroups;

    public WorkoutExercises() {
        // TODO Auto-generated constructor stub
    }

    public WorkoutExercises(int id, String name, String description, List<String> muscleGroups, String time, String level, String goal) {
        this.id = id;
        this.muscleGroups = muscleGroups;
        this.description = description;
        this.goal = goal;
        this.level = level;
        this.name = name;
        this.time = time;
    }

    public List<String> getMuscleGroups() {
        return muscleGroups;
    }

    public void setMuscleGroups(List<String> muscleGroups) {
        this.muscleGroups = muscleGroups;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getGoal() {
        return goal;
    }

    public void setGoal(String goal) {
        this.goal = goal;
    }

    public int getId() {
        return id;
    }

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

Java程序:

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class objectToJSON {

    public objectToJSON() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        String json = null;
        try {
            json = new String(Files.readAllBytes(Paths.get("C:\\Users\\data.json")));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Gson gson = new Gson();

        Type listType = new TypeToken<ArrayList<WorkoutExercises>>() {}.getType();
        ArrayList<WorkoutExercises> wk = gson.fromJson(json, listType);

        System.out.println(wk.get(0).getMuscleGroups());
    }
}

带有muscle_groups数组的JSON文件:

[
    {
        "id": 1,
        "name": "Push-Ups",
        "description": "Start in a plank position with your hands slightly wider than shoulder-width apart. Lower your body by bending your elbows until your chest nearly touches the floor. Push yourself back up to the starting position and repeat.",
        "muscle_groups": ["Chest", "Shoulders", "Triceps"],
        "time": "3 sets of 10 reps",
        "level": "Beginner",
        "goal": "Strength"
    },
    {
        "id": 2,
        "name": "Squats",
        "description": "Stand with your feet shoulder-width apart. Lower your body by bending your knees and pushing your hips back. Keep your chest up and your knees in line with your toes. Push through your heels to return to the starting position and repeat.",
        "muscle_groups": ["Quadriceps", "Hamstrings", "Glutes"],
        "time": "3 sets of 12 reps",
        "level": "Beginner",
        "goal": "Strength"
    },
    {
        "id": 3,
        "name": "Plank",
        "description": "Start in a push-up position with your hands directly under your shoulders. Engage your core and hold your body in a straight line from head to heels. Hold the position for the desired duration.",
        "muscle_groups": ["Core"],
        "time": "30 seconds",
        "level": "Beginner",
        "goal": "Core Stability"
    },
    {
        "id": 4,
        "name": "Lunges",
        "description": "Stand with your feet hip-width apart. Take a step forward with your right foot and lower your body until your right knee is bent at a 90-degree angle. Push through your right heel to return to the starting position and repeat on the other side.",
        "muscle_groups": ["Quadriceps", "Hamstrings", "Glutes"],
        "time": "3 sets of 10 reps per leg",
        "level": "Beginner",
        "goal": "Lower Body Strength"
    }
]
英文:

I import the latest version of GSON lib.
The console of the below java program show "null", but it's okay when i tried printing other attributes of the object. This means that the GSON function can parse the JSON element to Java object but it does not work with the muscle_groups attribute so the String[] return null.
i've tried changing the java datatype, also asked the chat GPT but still not working
I dont know how to fix this...

java object class


import java.util.ArrayList;
import java.util.List;
public class WorkoutExercises {
String name, description, time, level, goal;
int id;
List&lt;String&gt; muscleGroups;
public WorkoutExercises() {
// TODO Auto-generated constructor stub
}
public WorkoutExercises(int id, String name, String description,  List&lt;String&gt; muscleGroups, String tỉme, String level, String goal) {
this.id=id;
this.muscleGroups = muscleGroups;
this.description = description;
this.goal = goal;
this.level = level;
this.name =  name;
this.time = time;
}
public List&lt;String&gt; getMuscleGroups() {
return muscleGroups;
}
public void setMuscleGroups(List&lt;String&gt; muscleGroups) {
this.muscleGroups = muscleGroups;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getGoal() {
return goal;
}
public void setGoal(String goal) {
this.goal = goal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}	

java program:


import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import javax.lang.model.util.Elements;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class objectToJSON {
public objectToJSON() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String json = null;
try {
json = new String(Files.readAllBytes(Paths.get(&quot;C:\\Users\\data.json&quot;)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Gson gson = new Gson();
Type listType = new TypeToken&lt;ArrayList&lt;WorkoutExercises&gt;&gt;(){}.getType();
ArrayList&lt;WorkoutExercises&gt; wk = gson.fromJson(json, listType);
System.out.println(wk.get(0).muscleGroups);	
}
}

json file with muscle_groups array:

[
{
&quot;id&quot;: 1,
&quot;name&quot;: &quot;Push-Ups&quot;,
&quot;description&quot;: &quot;Start in a plank position with your hands slightly wider than shoulder-width apart. Lower your body by bending your elbows until your chest nearly touches the floor. Push yourself back up to the starting position and repeat.&quot;,
&quot;muscle_groups&quot;: [&quot;Chest&quot;, &quot;Shoulders&quot;, &quot;Triceps&quot;],
&quot;time&quot;: &quot;3 sets of 10 reps&quot;,
&quot;level&quot;: &quot;Beginner&quot;,
&quot;goal&quot;: &quot;Strength&quot;
},
{
&quot;id&quot;: 2,
&quot;name&quot;: &quot;Squats&quot;,
&quot;description&quot;: &quot;Stand with your feet shoulder-width apart. Lower your body by bending your knees and pushing your hips back. Keep your chest up and your knees in line with your toes. Push through your heels to return to the starting position and repeat.&quot;,
&quot;muscle_groups&quot;: [&quot;Quadriceps&quot;, &quot;Hamstrings&quot;, &quot;Glutes&quot;],
&quot;time&quot;: &quot;3 sets of 12 reps&quot;,
&quot;level&quot;: &quot;Beginner&quot;,
&quot;goal&quot;: &quot;Strength&quot;
},
{
&quot;id&quot;: 3,
&quot;name&quot;: &quot;Plank&quot;,
&quot;description&quot;: &quot;Start in a push-up position with your hands directly under your shoulders. Engage your core and hold your body in a straight line from head to heels. Hold the position for the desired duration.&quot;,
&quot;muscle_groups&quot;: [&quot;Core&quot;],
&quot;time&quot;: &quot;30 seconds&quot;,
&quot;level&quot;: &quot;Beginner&quot;,
&quot;goal&quot;: &quot;Core Stability&quot;
},
{
&quot;id&quot;: 4,
&quot;name&quot;: &quot;Lunges&quot;,
&quot;description&quot;: &quot;Stand with your feet hip-width apart. Take a step forward with your right foot and lower your body until your right knee is bent at a 90-degree angle. Push through your right heel to return to the starting position and repeat on the other side.&quot;,
&quot;muscle_groups&quot;: [&quot;Quadriceps&quot;, &quot;Hamstrings&quot;, &quot;Glutes&quot;],
&quot;time&quot;: &quot;3 sets of 10 reps per leg&quot;,
&quot;level&quot;: &quot;Beginner&quot;,
&quot;goal&quot;: &quot;Lower Body Strength&quot;
}
]

答案1

得分: 0

您的JSON文件使用muscle_groups作为字段名称,因此您的类必须相应地进行映射。<br/>
要做到这一点,您可以将您的Java字段对象重命名为muscle_groups,或者在JSON文件中更改为muscleGroups。<br/><br/>
您还可以强制进行映射,如下所示:

@SerializedName(value = "muscle_groups")
List<String> muscleGroups;

而不改变其他任何内容。<br/><br/>
实现您的目标的另一种方法是使用正确的FieldNamingPolicy

英文:

Your JSON file is using muscle_groups as the field name, so your class must be mapped accordingly.<br/>
To do so you can rename your java field object as muscle_groups, or change in the JSON file with muscleGroups.<br/><br/>
You can also force the mapping, like this:

@SerializedName(value = &quot;muscle_groups&quot;)
List&lt;String&gt; muscleGroups;

without changing anything else.<br/><br/>
Another way to achieve your goal is using the correct FieldNamingPolicy.

huangapple
  • 本文由 发表于 2023年6月8日 03:14:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426445.html
匿名

发表评论

匿名网友

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

确定