gpt4 book ai didi

java - 改造具有空字段的获取对象

转载 作者:行者123 更新时间:2023-12-02 02:05:03 24 4
gpt4 key购买 nike

我使用 Retrofit 2.4 并尝试从 Asp.Net Core 2.0 WebApi 服务获取数据。

这里是 Java 类:

public class Category {
private int CategoryID;
private String Name;
private String Image;

public Category(){
Name="";
Image="";
}

public Category(int categoryID, String name, String image) {
Name = name;
Image = image;
CategoryID=categoryID;
}

public int getCategoryID() {return CategoryID;}

public String getName() {
return Name;
}

public void setName(String name) {
Name = name;
}

public String getImage() {
return Image;
}

public void setImage(String image) {
Image = image;
}

}

此处改造代码:

public class Common {
public static User CURRENT_USER;
public static String SERVER_NAME="http://ip_address:5000";
public static IApiService ApiService;
public Common()
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_NAME)
.addConverterFactory(GsonConverterFactory.create())
.build();

ApiService = retrofit.create(IApiService.class);
}

}

public interface IApiService
{
@GET("api/Categories")
Call<List<Category>> GetCategoryColl();
}

然后我通过 Asp.Net Core 2.0 WebApi 编写服务器端。

我有一个 Controller :

   [Produces("application/json")]
[Route("api/Categories")]
public class CategoriesController : Controller
{
private readonly MovieAppServerContext _context;

public CategoriesController(MovieAppServerContext context)
{
_context = context;
}

// GET: api/Categories
[HttpGet]
public IEnumerable<Category> GetCategory()
{
return _context.Category;
}

// GET: api/Categories/5
[HttpGet("{id}")]
public async Task<IActionResult> GetCategory([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);

if (category == null)
{
return NotFound();
}

return Ok(category);
}

// PUT: api/Categories/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCategory([FromRoute] int id, [FromBody] Category category)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

if (id != category.CategoryID)
{
return BadRequest();
}

_context.Entry(category).State = EntityState.Modified;

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CategoryExists(id))
{
return NotFound();
}
else
{
throw;
}
}

return NoContent();
}

// POST: api/Categories
[HttpPost]
public async Task<IActionResult> PostCategory([FromBody] Category category)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

_context.Category.Add(category);
//await _context.SaveChangesAsync();
_context.SaveChanges();

return Ok(category);
}

// DELETE: api/Categories/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCategory([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);
if (category == null)
{
return NotFound();
}

_context.Category.Remove(category);
// await _context.SaveChangesAsync();
_context.SaveChanges();

return Ok("Removed!");
}

private bool CategoryExists(int id)
{
return _context.Category.Any(e => e.CategoryID == id);
}
}

这里是类别的服务器端类:

  public class Category
{
[Key]
public int CategoryID { get; set; }

public String Name { get; set; }
public String Image { get; set; }

public Category()
{
}

public Category(String name, String image)
{
Name = name;
Image = image;
}
}

所以,我通过 Swagger 检查服务器代码,它运行良好:我从类别列表中获取所有数据。但是,当我尝试通过 Retrofit 从 Android 代码获取数据时 - 我得到包含空对象的集合:所有字段均为 null 或为空(我认为这是默认值)。

所以,这里是代码:

public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

List<Category> _categoryList =new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//some code
Common.ApiService.GetCategoryColl().enqueue(new Callback<List<Category>>() {
@Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
Log.i("GetCategories",response.message());
_categoryList=response.body();
// !!!! HERE. _category list contains objects but all of them
// are empty!



}

@Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Log.e("GetCategories",t.getMessage());
}
});
}
}

所以,我不知道为什么会发生这种情况?如何解决这个问题?谢谢!

最佳答案

您尚未将 @SerializedName("json-key-name") 添加到 Java Category 类中的字段:

@SerializedName("categoryId")
private int CategoryID;

@SerializedName("name")
private String Name;

@SerializedName("image")
private String Image;

现在 GSON 可以正确地将 JSON 响应映射到 POJO。

关于java - 改造具有空字段的获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com